Java无类型泛型类,删除它们的功能泛型类型
Ok有关javas泛型,iterable和for-each循环的问题。问题在于,如果我声明我的'测试'类是无类型的,那么我将失去关于我所有函数的所有通用信息,因为每个函数都不会这样。Java无类型泛型类,删除它们的功能泛型类型
例
public class Test<T> implements Iterable<Integer>{
public Test() {}
public Iterator<Integer> iterator() {return null;}
public static void main(String[] args) {
Test t = new Test();
//Good,
//its returning an Iterator<object> but it automatically changes to Iterator<Integer>
Iterator<Integer> it = t.iterator();
//Bad
//incompatable types, required Integer, found Object
for(Integer i : t){
}
}Untyped generic classes losing
}
当 '测试T' 是非类型化的,则 '迭代()' 功能返回 '游标' 而不是 '迭代<整数>'。
我不完全确定它背后的原因,我知道一个解决方案就是在测试<上使用通配符? > t = new test()'。然而,这不是理想的解决方案。
他们有什么办法只编辑类声明及其函数,并为每个循环工作无类型?
你应该只做到以下几点:
public class Test implements Iterable<Integer>{
删除泛型类型都在一起。你的Test
类是不通用的。它只是实现一个通用接口。声明一个泛型类型是没有必要的。这也将有利于删除您所得到的通用警告。
@Eugene说得很好。如果你其实想一个通用Test
类型,应声明Test
作为一个通用的迭代:
你应该只做到以下几点:
public class Test implements Iterable<Integer>{
删除泛型类型都在一起。你的Test
类是不通用的。它只是实现一个通用接口。声明一个泛型类型是没有必要的。这也将有利于删除您所得到的通用警告。
public class Test<T> implements Iterable<T>{
,然后确保你Test
通用的,当你实例化。
Test<Integer> t = new Test<Integer>;
然后调用for(Integer i: t)
将编译。
您应该这样写:
public class Test implements Iterable<Integer>{
...
或实际泛型化类:
public class Test<T> implements Iterable<T> {
public Iterator<T> iterator() {return null;}
public static void main(String[] args) {
Test<Integer> t = new Test<Integer>();
Iterator<Integer> it = t.iterator();
for(Integer i : t){
}
}
}
正是我开始写的。 +1 – 2010-12-14 21:02:35
是的,可以工作,但你可以遇到类似的情况。 “public class Vertex
这是完全不同的问题。在这种情况下,你的iterator()方法必须返回Iterator
如果使用原始类型,在方法仿制药将被忽略(见最新的Java谜题分期付款)。不要使用原始类型。最近版本的javac应该给出警告。 – 2010-12-15 01:04:24
感谢您的视频链接,在他们的非常有趣的东西。 >背后的推理现在变得更加流行。 – user542481 2010-12-15 18:20:54