Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

java - Wildcards with diamond operator

If I am trying to do something like this :

List<?> unknownList = new ArrayList<>();

then the code compiles and runs fine, but of which type the ArrayList has created?

and after this line, If I have done like this :

        unknownList.add("str"); //compilation error

It gives compilation error :

error: no suitable method found for add(String)
        unList.add("str");
              ^
method List.add(int,CAP#1) is not applicable
  (actual and formal argument lists differ in length)
method List.add(CAP#1) is not applicable
  (actual argument String cannot be converted to CAP#1 by method invocation conversion)
method Collection.add(CAP#1) is not applicable
  (actual argument String cannot be converted to CAP#1 by method invocation conversion)
where CAP#1 is a fresh type-variable:
    CAP#1 extends Object from capture of ?

What is this error, and is it good to use the diamond-operator with wildcards? If YES then WHERE???

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

but of which type was the ArrayList created?

Type parameters are just constraints applied at compile time, but type erasure replaces all occurrences of the type parameter by its erasure (in your case, Object). So, if you're asking about the runtime type, it will be a plain ArrayList (which you can think of as ArrayList<Object>).

is it good to use the diamond-operator with wildcards? If YES then WHERE???

No. When you use a diamond operator to create a new object of a generic class, it means you don't want to be redundant on the type parameter. It should not be combined with a wildcard-declared variable, which does not have a concrete type parameter.

To summarize, you should never write:

List<?> unknownList = new ArrayList<>();

You should only use the wild card <?> when the type really does not matter. In particular, don't use the wild card if you want to add items to the list, because adding items means you know what type to add.

It is likely to be used as a parameter of a method for instance, when you don't access the value and just pass the list on, or where you just access the list items as plain Objects.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...