Why are these invalid in Java?

List<Object> myList = new ArrayList<String>(); //(hint: no)
List<Object> myList = new ArrayList<String>(); //(hint: no)
Map<Integer> myMap = new HashMap<int>(); // (hint: also no)

Why is the statement in the above statement wrong?

Solution

Let's look at the first example Consider what you should be able to do on list < Object >: add, delete, retrieve any object

You are trying to populate these requirements with collections that can add, delete, and retrieve strings only

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 reason is simply that generics in java do not support basic types For more information, you can view:

java – Why don’t Generics support primitive types?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>