简体   繁体   中英

How do I make a list of several kind of object if I cannot use wildcards?

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> <? extends Parent> , since I do add .

But, I cannot use <? super Parent> <? 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?

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM