1

I want to make a List which can hold two kind of Object. What comes in my mind is to use wildcard. Below is my code.

public class Parent {
  //code  
}

public class ChildOne extends Parent {
  //code
}

public class ChildTwo extends Parent {
  //code
}

public class Implementation {

  List<? extends Parent> list;

  public Implementation() {

    list.add(new ChildOne());
    list.add(new ChildTwo());

    ChildOne co = list.get(0);
    ChildTwo ct = list.get(1);

  }

}

I cannot use <? extends Parent>, since I do add.

But, I cannot use <? super Parent> either, since I do get.

This question stated: don't use a wildcard when you both get and put..

So, how do I do to make a list of several kind of Object without using wildcards?

Community
  • 1
  • 1
Gustaf
  • 262
  • 1
  • 13

2 Answers2

2

Wild cards is not appropriate for this use case. You should simply do

List<Parent> list = new ArrayList<>();

and cast the return value from get:

ChildOne co = (ChildOne) list.get(0);
ChildTwo ct = (ChildTwo) list.get(1);
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • knowing the solution is so damn simple, I feel kind of silly thinking I need wildcard for this kind of thing. – Gustaf May 11 '15 at 07:41
2

You can just create your list this way:

List<Parent> list = new ArrayList<>();
list.add(new ChildOne());
list.add(new ChildTwo());

Now you can add and get any object that is (or extends) Parent.

Take in mind that you need to cast the object to the proper one when you get it.

ChildOne co = (ChildOne) list.get(0);
ChildTwo ct = (ChildTwo) list.get(1);
Kiril Aleksandrov
  • 2,601
  • 20
  • 27