因此,这是什么时候的教程说
我想是的,虽然有几个陷阱的当谈到<>
运营商的意思。
对于您的情况,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