因此,這是什麼時候的教程說
我想是的,雖然有幾個陷阱的當談到<>
運營商的意思。
對於您的情況,Box實例化是一個非問題,因爲可以使用構造函數參數輕鬆推斷該類型。嘗試更改構造函數爲「不」,請參閱Integer
或T
並查看調用失敗的方式。
class BadBox<T> {
private T t;
public BadBox(){}
public void setT(T t) {
this.t = t;
}
static void f(BadBox<Integer> box){}
public static void main(final String[] args) {
f(new BadBox<>()); //fails, should have worked ideally
}
}
同樣,看一下這個類:
class Testi<R> {
public void doIt(Set<? extends R> sets) {
}
public static void main(final String[] args) {
// works since type inference is now possible
new Testi<CharSequence>().doIt(new HashSet<>(Arrays.asList("a")));
// fails; nothing which can help with type inference
new Testi<CharSequence>().doIt(new HashSet<>();
}
}
同樣,在你的鏈接的問題(關於addAll
)的問題可以簡單地通過幫助了編譯器一點如下解決:
List<String> 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<String>()));
鑽石運營商也似乎打破,當談到實現匿名類,如下所示:
final String[] strings = { "a", "b", "c" };
Arrays.sort(strings, new Comparator<>() {
@Override
public int compare(String o1, String o2) {
return 0;
}
});
幸運的是,在這種情況下,編譯器非常明確地提到<>
不適用於匿名類。
@gurung了一個錯字。切不好的情況下,粘貼:( – 2011-12-26 17:02:54