Java泛型:通配符捕获误解 [英] Java Generics: Wildcard capture misunderstanding

查看:359
本文介绍了Java泛型:通配符捕获误解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读Java在线教程,我对通配符捕获并不了解。
例如:

  import java.util.List; 
public class WildcardError {
void foo(List<> i){
i.set(0,i.get(0));
}
}

为什么编译器不能保证赋值的安全?
它知道,通过执行具有整数列表的方法,它从i.get获得一个整数值。所以它试图将索引0处的整数值设置为相同的整数列表(i)。
那么,怎么回事?为什么编写通配符助手?

解决方案


为什么编译器可以't保留赋值安全吗?

编译器不知道什么关于元素类型列表与LT;?>我,根据的定义。通配符不是,而是的意思是任何类型;它意味着一些未知类型。它知道,通过执行例如带有整数列表的方法,它从i中获得.get a Integer value。


确实如此,但正如我上面所说:编译器只能知道知道 - 在编译时,记住 - i.get(0)返回一个 Object ,这是的上限。但是不能保证在运行时是 Object ,所以没有办法编译器知道 i.set(0,i.get(0))是安全的调用。就像这样写:

  List< Foo> fooz = / * init * /; 
Object foo = fooz.get(0);
fooz.set(0,foo); //不会编译,因为foo是一个对象,而不是Foo



更多阅读:




Reading the Java online tutorial i haven't understand anything about wildcard capture. For example:

    import java.util.List;
    public class WildcardError {
     void foo(List<?> i) {
      i.set(0, i.get(0));
     }
    }

why the compiler can't retain the assignment safe? It knows that,by executing for instance, the method with an Integer List, it gets from i.get an Integer value. So it try to set an Integer value at index 0 to the same Integer list (i). So,what's wrong?Why write Wildcard helper?

解决方案

why the compiler can't retain the assignment safe?

The compiler doesn't know anything about the type of elements in List<?> i, by definition of ?. Wildcard does not mean "any type;" it means "some unknown type."

It knows that,by executing for instance, the method with an Integer List, it gets from i.get an Integer value.

That's true, but as I said above: the compiler can only know – at compile time, remember – that i.get(0) returns an Object, which is the upper bound of ?. But there's no guarantee that ? is at runtime Object, so there is no way for the compiler to know that i.set(0, i.get(0)) is a safe call. It's like writing this:

List<Foo> fooz = /* init */;
Object foo = fooz.get(0);
fooz.set(0, foo); // won't compile because foo is an object, not a Foo

More reading:

这篇关于Java泛型:通配符捕获误解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆