Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type returns the get method?

If the type variable is a wildcard, what return type of the method will be?

public class MyClass{ }

List<? extends MyClass> nms = new ArrayList<MyClass>();
nms.add(new MyClass()); //compilation error
MyClass n = nms.get(0); //compiles fine

The thing is the return type of the get is not the pure MyClass type. Eclipse's telling me that it's CAP#2 and the argument of the add method is CAP#1 where CAP#2 is a subtypeof MyClass, but MyClass is not a subtypeof CAP#1?

So, I'm interested where for compiler the captured type is in class hierarchy? If we create

public class MySubClass extends MyClass{ }

will CAP#2 be a subtype of MySubClass either?

like image 371
user3663882 Avatar asked Sep 11 '26 17:09

user3663882


2 Answers

Even if you know that

class MySubClass extends MyClass{ }

the compiler is not entirely sure that the object you want to add to the list is compliant with the restriction of unknown subtype of MyClass, because nothing ca guarantee that "unknown" can be MySubClass. Therefore, it raises an error.

This is well-known as PECS.

So, having your list define as:

List<? extends MyClass> nms = new ArrayList<MyClass>();

you will be able to add nothing but the null reference, because it's the only compliant with "unknown"

like image 96
Konstantin Yovkov Avatar answered Sep 14 '26 08:09

Konstantin Yovkov


No, <? extends MyClass> is an unknown class that extends MyClass (can be MyClass itself). There is no guarantee that it has any relationship to MySubClass.

Replace MyClass with Number and MySubClass with BigDecimal. Then you have <? extends Number>. That could be Long. Long has nothing to do with BigDecimal (even though both extend Number).

As for the two methods, get will return something that is a MyClass. add will only accept instances of the unknown type (and since the compiler cannot enforce much about unknown types, it won't let you add anything except null).

like image 35
Thilo Avatar answered Sep 14 '26 06:09

Thilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!