Wildcard <?>

2022. 2. 22. 18:35·Programming/Java

와일드카드란?

The wildcard ? in Java is a special kind of type argument[1] that controls the type safety of the use of generic (parameterized) types. It can be used in variable declarations and instantiations as well as in method definitions, but not in the definition of a generic type.[

 

 

public static<T> void peekBox(Box<T> box){
	System.out.println(box);	
}// 제네릭 메소드 정의

public static void peekBox(Box<?> box){
	System.out.println(box);	
}// 제네릭 메소드 정의

- 기능적으로 두 메소드 완전 동일

- 와일드카드의 코드가 간결하므로 권고

 

 

와일드카드와 상속

1. Upper Bounded Wildcards

- 상한 제한된 와일드 카드

2. Lower Bounded Wildcards

- 하한 제한된 와일드 카드

 

Upper Bounded Wildcards

- <? extends Number>

- 타입 인자를 Number을 상속하는 클래스 타입으로 제한

- 상한 제한의 의미: Number을 상한으로 제한

 

Lower Bounded Wildcards

- <? super Integer>

- 타입 인자를 Integer가 상속하는 클래스 타입(Integer의 상위 클래스: Number, Object, ...)으로 제한

- 하한 제한으 의미: Integer을 하한으로 제한

 

와일드카드 제한 도입 이유

- 프로그래머의 실수가 컴파일 오류로 들어나지 않는다.

- 안정성을 높일 수 있다.


상한 제한의 목적

왜 set()이 컴파일 에러가 발생할까?

- outBox(Box<? extends Toy> box)에 Box<Car> 또는 Box<Robot> 인스턴스의 전달을 가정해보자. 

- box.set(new Toy())의 로직은 Robot ob= new Toy()을 의미한다. 

- 참조 변수의 타입은 부모 클래스 타입의 인스턴스를 인자로 전달 받을 수 없다. 


하한 제한의 목적

왜 get()이 컴파일 에러가 발생할까?

- Box<Plastic>. 즉, Toy의 상위 클래스를 타입 인자로 갖는 인스턴스의 전달을 가정해보자. 

- Toy myToy= box.get()에서 box.get()의 자료형은 Plastic이다. 

- 참조 변수의 타입은 부모 클래스 타입의 인스턴스를 인자로 전달 받을 수 없다. 


정리

- <? extends Toy>: 꺼내기만 가능(read)

- <? super Toy>: 넣가만 가능(write)

- 컴파일을 통해 프로그래머의 실수를 거를 수 있다.

'Programming > Java' 카테고리의 다른 글

ArrayList vs LinkedList  (0) 2022.02.23
Collections.sort()  (0) 2022.02.23
Generic Method (Basic)  (0) 2022.02.22
Generic Class (Basic)  (0) 2022.02.22
Collection  (0) 2022.02.11
'Programming/Java' 카테고리의 다른 글
  • ArrayList vs LinkedList
  • Collections.sort()
  • Generic Method (Basic)
  • Generic Class (Basic)
사랑우주인
사랑우주인
  • 사랑우주인
    lovelyAlien
    사랑우주인
  • 전체
    오늘
    어제
  • 글쓰기
    관리
    • 분류 전체보기 (209)
      • Programming (4)
        • Spring (28)
        • Java (46)
        • JPA (2)
        • 디자인 패턴 (5)
        • 개발&아키텍처 (0)
      • Network (14)
      • OS (19)
      • Database (1)
      • Kubernetes (0)
      • Kafka (2)
      • Algorithm (49)
        • BaekJoon (1)
        • Programmers (19)
        • Algorithm (5)
        • Socar (2)
        • LeetCode (19)
      • Interview (2)
      • Issues (2)
      • DotJoin (1)
      • Git (4)
      • 독서 (3)
      • 끄적끄적 (1)
      • 외부활동 (26)
        • 항해플러스 (2)
        • JSCODE 네트워크 (19)
        • JSCODE 자바 (5)
      • SQL (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • GitHub
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    JSCode
    RR
    디자인 패턴
    @JsonProperty
    제네릭
    @JsonNaming
    Generic
    OS
    algorithm
    Reorder List
    Oauth2
    LinkedList
    wildcards
    socar
    준영속 엔티티
    minimum number of arrows to burst balloons
    Climbing Stairs
    Process
    fcfs
    트랜잭션
    pacific atlantic water flow
    runner 기법
    rotting oranges
    clone graph
    추상화 클래스
    lower bounded wildcards
    BFS
    Thread
    AuthenticationSuccessHandler
    운영체제
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.1
사랑우주인
Wildcard <?>
상단으로

티스토리툴바