How to cast List<Object> to List

后端 未结 16 927
时光取名叫无心
时光取名叫无心 2020-11-27 11:43

This does not compile, any suggestion appreciated.

 ...
  List list = getList();
  return (List) list;


Compil

16条回答
  •  难免孤独
    2020-11-27 12:13

    Note that I am no java programmer, but in .NET and C#, this feature is called contravariance or covariance. I haven't delved into those things yet, since they are new in .NET 4.0, which I'm not using since it's only beta, so I don't know which of the two terms describe your problem, but let me describe the technical issue with this.

    Let's assume you were allowed to cast. Note, I say cast, since that's what you said, but there are two operations that could be possible, casting and converting.

    Converting would mean that you get a new list object, but you say casting, which means you want to temporarily treat one object as another type.

    Here's the problem with that.

    What would happen if the following was allowed (note, I'm assuming that before the cast, the list of objects actually only contain Customer objects, otherwise the cast wouldn't work even in this hypothetical version of java):

    List list = getList();
    List customers = (List)list;
    list.Insert(0, new someOtherObjectNotACustomer());
    Customer c = customers[0];
    
    
    

    In this case, this would attempt to treat an object, that isn't a customer, as a customer, and you would get a runtime error at one point, either form inside the list, or from the assignment.

    Generics, however, is supposed to give you type-safe data types, like collections, and since they like to throw the word 'guaranteed' around, this sort of cast, with the problems that follow, is not allowed.

    In .NET 4.0 (I know, your question was about java), this will be allowed in some very specific cases, where the compiler can guarantee that the operations you do are safe, but in the general sense, this type of cast will not be allowed. The same holds for java, although I'm unsure about any plans to introduce co- and contravariance to the java language.

    Hopefully, someone with better java knowledge than me can tell you the specifics for the java future or implementation.

    提交回复
    热议问题