Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Collections using wildcard

Tags:

java

public static void main(String[] args) {

    List<? extends Object> mylist = new ArrayList<Object>();

    mylist.add("Java"); // compile error

}

The above code does not allow you to add elements to the list and wild cards can only be used as a signature in methods, again not for adding but only for accessing. In this case what purpose does the above fulfil ??

like image 324
Omnipotent Avatar asked Feb 04 '23 13:02

Omnipotent


1 Answers

Let's say you have an interface and two classes:

interface IResult {}
class AResult implements IResult {}
class BResult implements IResult {}

Then you have classes that return a list as a result:

interface ITest<T extends IResult> {
  List<T> getResult();
}

class ATest implements ITest<AResult> {
  // look, overridden!
  List<AResult> getResult();
}

class BTest implements ITest<BResult> {
  // overridden again!
  List<BResult> getResult();
}

It's a good solution, when you need "covariant returns", but you return collections instead of your own objects. The big plus is that you don't have to cast objects when using ATest and BTest independently from the ITest interface. However, when using ITest interface, you cannot add anything to the list that was returned - as you cannot determine, what object types the list really contains! If it would be allowed, you would be able to add BResult to List<AResult> (returned as List<? extends T>), which doesn't make any sense.

So you have to remember this: List<? extends X> defines a list that could be easily overridden, but which is read-only.

like image 57
rmaruszewski Avatar answered Feb 06 '23 11:02

rmaruszewski