What are the risks of explicitly casting from a list of type List<? extends MyObject> to a list of type List in Java?

后端 未结 5 1163
说谎
说谎 2021-01-12 16:26

I think the title should explain it all but just in case...

I want to know what risks and potential issues relating to casting can arise from the following snippet o

相关标签:
5条回答
  • 2021-01-12 16:27

    Consider you do something like:

    List<ChildClassOne> childClassList = new ArrayList<ChildClassOne>();
    childClassList.add(childClassOneInstanceOne);
    childClassList.add(childClassOneInstanceTwo);
    
    List<? extends MyObject> wildcardList = childClasslist; // works fine - imagine that you get this from a method that only returns List<ChildClassOne>
    List<MyObject> typedList = (List<MyObject>) wildcardList; // warning
    
    typedList.add(childClassTwoInstanceOne); // oops my childClassList now contains a childClassTwo instance
    ChildClassOne a = childClassList.get(2); // ClassCastException - can't cast ChildClassTwo to ChildClassOne
    

    This is the only major problem. But if you only read from your list it should be ok.

    0 讨论(0)
  • 2021-01-12 16:27

    This is similar to

    List<Object> obj = (List<Object>) new ArrayList<String>();
    

    I hope the problem is evident. List of subtypes can't be cast to Lists of supertypes.

    0 讨论(0)
  • 2021-01-12 16:29

    In addition to the answers already posted, take a look at the following

    • what-is-the-meaning-of-the-type-safety-warning-in-certain-java-generics-casts
    • confused-by-java-generics-requiring-a-cast

    The compiler generates a warning incase an element from the type is accessed later in your code and that is not the generic type defined previously. Also the type information at runtime is not available.

    0 讨论(0)
  • 2021-01-12 16:34

    There should be no problem as long as just you retrieve objects from the list. But it could result in runtime exception if you invoke some other methods on it like the following code demonstrate:

        List<Integer> intList = new ArrayList<Integer>();
        intList.add(2);
    
        List<? extends Number> numList = intList;
        List<Number> strictNumList = (List<Number>) numList;
        strictNumList.add(3.5f);
    
        int num = intList.get(1); //java.lang.ClassCastException: java.lang.Float cannot be cast to java.lang.Integer
    
    0 讨论(0)
  • 2021-01-12 16:39

    You are correct about retrieving objects from typedList, this should work.

    The problem is when you later add more objects to typedList. If, for instance, MyObject has two subclasses A and B, and wildcardList was of type A, then you can't add a B to it. But since typedList is of the parent type MyObject, this error will only be caught at runtime.

    0 讨论(0)
提交回复
热议问题