开发者

Why are these invalid in Java?

开发者 https://www.devze.com 2023-03-11 17:17 出处:网络
List<Object> myList = new Arr开发者_运维技巧ayList<String>(); //(hint: no) Map<Integer> myMap = new HashMap<int>(); // (hint: also no)
List<Object> myList = new Arr开发者_运维技巧ayList<String>(); //(hint: no)
Map<Integer> myMap = new HashMap<int>(); // (hint: also no)

Why are the statements wrong in the above declarations?


Let's look at the first example. Think of the operations you should be able to do on a List<Object>: Add, Remove, Retrieve any Object.

You're trying to fill those requirements with a collection that you can Add, Remove, and Retrieve only strings.

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

// This should be valid based on the List<Object> interface but obviously
// MyClass isn't String...so what would the statement do?
myList.add(new MyClass());

The second is simply because Generics in Java don't support primitive types. For more information, you could check out:

java - Why don't Generics support primitive types?


For the first one, because Java generics are not covariant. So you can't even do:

ArrayList<Object> myList = new ArrayList<String>();

For more info, see this article: Java theory and practice: Generics gotchas.

For the second one, you cannot use primitives as the generic type.


1) What would happen if anyone added a Long to the list that is referenced by myList?

2) You can't have a primitive there.


  1. The first is impossible. You can use a wildcard:

    List<?> myList = new ArrayList<String>();
    

    But now, your list is completely unusable. Adding, removing, etc doesn't compile anymore:

    myList.add(new Object()); // Error
    myList.add("error");      // Error
    
  2. You can't use primitives (int, double, ....) with generics. You have to use the wrapper class:

    HashMap<Integer> myHap = new HashMap<Integer>();
    


for the second example Map has 2 generic parameters a Key and Value but the following still wont work

Map<Integer,Object> myMap = new HashMap<int,Object>();

that because as said before primitive types don't work with java generics (besides generic types always derive from Object and type erasure translates all generic variables to type Object)


For all things Java-Generics, refer to Angelika Langer. In this case, Is List<Object> a supertype of List<String>?

Even though Java does support auto-boxing, it doesn't automatically convert <int> to <Integer>. IMO this is partly to remind users that you can get nulls.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号