Java Collections using wildcard

前端 未结 7 1524
天命终不由人
天命终不由人 2020-12-11 03:26
public static void main(String[] args) {

    List mylist = new ArrayList();

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

}
         


        
      
      
      
7条回答
  •  [愿得一人]
    2020-12-11 03:50

    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 {
      List getResult();
    }
    
    class ATest implements ITest {
      // look, overridden!
      List getResult();
    }
    
    class BTest implements ITest {
      // overridden again!
      List 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 (returned as List), which doesn't make any sense.

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

提交回复
热议问题