Java using generics with lists and interfaces

后端 未结 6 1745
遇见更好的自我
遇见更好的自我 2021-01-13 11:02

Ok, so here is my problem:

I have a list containing interfaces - List a - and a list of interfaces that extend that interface: Li

6条回答
  •  离开以前
    2021-01-13 11:49

    This works :

    public class TestList {
    
        interface Record {}
        interface SubRecord extends Record {}
    
        public static void main(String[] args) {
            List l = new ArrayList();
            List l2 = new ArrayList();
            Record i = new Record(){};
            SubRecord j = new SubRecord(){};
    
            l = l2;
            Record a = l.get( 0 );
            ((List)l).add( i );       //<--will fail at run time,see below
            ((List)l).add( j );    //<--will be ok at run time
    
        }
    
    }
    

    I mean it compiles, but you will have to cast your List before adding anything inside. Java will allow casting if the type you want to cast to is a subclass of Record, but it can't guess which type it will be, you have to specify it.

    A List can only contain Records (including subRecords), A List can only contain SubRecords.

    But A List> is not a List has it cannot contains Records, and subclasses should always do what super classes can do. This is important as inheritance is specilisation, if List would be a subclass of List, it should be able to contain ` but it'S not.

    A List and a List both are List. But in a List you can't add anything as java can't know which exact type the List is a container of. Imagine you could, then you could have the following statements :

    List l = l2;
    l.add( new Record() );
    

    As we just saw, this is only possible for List not for any List such as List.

    Regards, Stéphane

提交回复
热议问题