2

好的关于 javas 泛型、可迭代和 for-each 循环的问题。问题是,如果我声明我的“测试”类没有类型,我会丢失所有函数的所有通用信息,并且 for-each 根本不喜欢这样。

例子

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 
}

当 'Test t' 没有类型时,'iterator()' 函数返回 'iterator' 而不是 'iterator < Integer >'。

我不确定它背后的原因,我知道一个解决方法就是在 'Test < 上使用通配符?> t = 新测试()'。然而,这是一个不太理想的解决方案。
他们有什么方法可以只编辑类声明及其函数并让 for each 循环工作无类型?

4

2 回答 2

3

您应该执行以下操作:

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)将编译。

于 2010-12-14T20:56:09.123 回答
2

你应该这样写:

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){
        }
    } 
}
于 2010-12-14T21:01:25.143 回答