Java - Generics with lists

后端 未结 5 1011
悲&欢浪女
悲&欢浪女 2020-12-21 13:52

I wrote a function for my cache to retrieve a specific object. This way I don\'t need to cast it .

@SuppressWarnings(\"unchecked\")
    public static 

        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-21 14:16

    Just to clarify Joe's answer ( I don't have enough reputation to comment), at runtime there is no difference between a List and List or any other type of List, generics aren't kept at runtime.

    Meaning, List.class is completely identical to List.class and is actually List.class. This is a weakness of the Java type system. I'm not familiar with a simple way to implement what you wish for.

    A code proof for the heck of it :

    // It is true that      
        List stringList = new ArrayList(); 
        List integerList = new ArrayList();                                               
        System.out.println( stringList.getClass() == integerList.getClass()  );
    
        // And that ... 
        List objectList = new ArrayList();
        System.out.println( stringList.getClass() == objectList.getClass()  );
    
        //However, the following is false because a different implementation is used ( I wanted a false case)
        List objectLinkedList = new LinkedList();
        System.out.println(  objectLinkedList.getClass() == objectList.getClass() );
    

提交回复
热议问题