Covariance and Contravariance in Java
11934 단어 Java
extends
The wildcard declaration of
List extends Number> foo3
means that any of these are legal assignments: List extends Number> foo3 = new ArrayList<Number>(); // Number "extends" Number (in this context)
List extends Number> foo3 = new ArrayList<Integer>(); // Integer extends Number
List extends Number> foo3 = new ArrayList<Double>(); // Double extends Number
Reading - Given the above possible assignments, what type of object are you guarenteed to read from
List foo3
: You can read a
Number
because any of the lists that could be assigned to foo3
contain a Number
or a subclass of Number
. You can't read an
Integer
because foo3
could be pointing at a List
. You can't read a
Double
because foo3
could be pointing at a List
. Writing - Given the above possible assignments, what type of object could you add to
List foo3
that would be legal for all the above possible ArrayList
assignments: You can't add an
Integer
because foo3
could be pointing at a List
. You can't add a
Double
because foo3
could be pointing at a List
. You can't add a
Number
because foo3
could be pointing at a List
. You can't add any object to
List extends T>
because you can't guarantee what kind of List
it is really pointing to, so you can't guarantee that the object is allowed in that List
. The only "guarantee" is that you can only read from it and you'll get a T
or subclass of T
. super
Now consider
List super T >
. The wildcard declaration of
List super Integer> foo3
means that any of these are legal assignments: List super Integer> foo3 = new ArrayList<Integer>(); // Integer is a "superclass" of Integer (in this context)
List super Integer> foo3 = new ArrayList<Number>(); // Number is a superclass of Integer
List super Integer> foo3 = new ArrayList<Object>(); // Object is a superclass of Integer
Reading - Given the above possible assignments, what type of object are you guaranteed to receive when you read from
List foo3
: You aren't guaranteed an
Integer
because foo3
could be pointing at a List
or List
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.