This is kind of a follow up question on the discussion:
From the Java Tutorial,
Note that the diamond often works in method calls; however, for greater clarity, it is suggested that you use the diamond primarily to initialize a variable where it is declared
So, I am a bit confused about the first line. When does diamond work in method calls?
A bit more explanation on how diamond operator works can be found here:
And from this, I have tried the following, which works fine:
Give that I have:
private static class Box{
public Box(T t){}
}
static void f(Box box){}
a call like the following compiles fine:
f(new Box<>(new Integer(10)));
The type parameter in invoking the constructor in the method call of f() above is inferred from the argument to the constructor (i.e. Integer).
So is this what is meant when the tutorial says
Note that the diamond often works in method calls
If not, can anyone kind enough to provide an example where diamond works in method call?
解决方案
So is this what is meant when the tutorial says
I think yes though there are a couple of gotchas when it comes to <> operators.
In your case, Box instantiation is a non-issue given that the type can be trivially inferred using the constructor argument. Try changing the constructor to "not" take in an Integer or T and see how the invocation fails.
class BadBox {
private T t;
public BadBox(){}
public void setT(T t) {
this.t = t;
}
static void f(BadBox box){}
public static void main(final String[] args) {
f(new BadBox<>()); //fails, should have worked ideally
}
}
Similarly, have a look at this class:
class Testi {
public void doIt(Set extends R> sets) {
}
public static void main(final String[] args) {
// works since type inference is now possible
new Testi().doIt(new HashSet<>(Arrays.asList("a")));
// fails; nothing which can help with type inference
new Testi().doIt(new HashSet<>();
}
}
Similarly, the problem in your linked question (regarding addAll) can be simply solved by helping out the compiler a bit as follows:
List list = new ArrayList<>();
list.add("A");
// works now! use only if you love diamond operator ;)
list.addAll(new ArrayList<>(Arrays.asList(new String[0])));
// or the old-school way
list.addAll(new ArrayList()));
Diamond operators also seem to break when it comes to implementing anonymous classes as follows:
final String[] strings = { "a", "b", "c" };
Arrays.sort(strings, new Comparator<>() {
@Override
public int compare(String o1, String o2) {
return 0;
}
});
Fortunately, in this case, the compiler is pretty explicit in mentioning that <> doesn't/won't work with anonymous classes.