Java – primitive types and in generics Differences between

It may be asked somewhere, but I can't find it

Please tell me the exact difference between the two:

ArrayList list = new ArrayList();

and

ArrayList<?> list = new ArrayList();

I can't figure out the exact difference between the two

Thank you

Solution

ArrayList Simply means "any type" In other words, any type of ArrayList can be assigned to such a variable This can be ArrayList < integers >, ArrayList < JButton >, or anything else Using wildcards alone without the keyword super (followed by type) means that you can't add anything to an array defined as ArrayList In the list of However, ArrayList itself means the old typeless ArrayList. You can perform various operations, including adding

List<?> list;
List<Integer> ints = new ArrayList<Integer>();
List<Integer> strings = new ArrayList<Integer>();
list = ints; // valid
list = strings; // valid
list.add("new"); // compile error

to update:

Suppose I have the following methods:

void insert(List list) {
   // loop through list,do whatever you like
   list.add("my string"); // dangerous operation 
}

Now, if I call insert (ints), the compiler will generate a warning, but it won't prevent me from adding string to the integer list The change method is as follows:

void insert(List<?> list) {
   // loop through list,do whatever you like
   list.add("my string"); // compiler error on this dangerous operation
}

Will prevent me from doing so

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
分享
二维码
< <上一篇
下一篇>>