迭代器未迭代Java中的类

import java.util.*;

class Person{
    private String name;
    private int age;
    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
}


public class Iterator {
    public static void main(String args[]) {
        Collection<Person> collection = new ArrayList<Person>();
        collection.add(new Person("Komal",45));
        collection.add(new Person("Rahul",34));
        collection.add(new Person("Rakesh",27));
        Iterator iterator = collection.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

输出: 线程“主”中的异常java.lang.Error:未解决的编译问题:     Iterator类型不是通用的;不能使用参数对其进行参数化

at java_classes.Iterator.main(Iterator.java:37)

因此,当我如上所述运行此代码时,如何使用Iterator作为显示错误来迭代类人。

评论
Finn
Finn

Your class name is Iterator, that shadows java.util.Iterator. You could rename your class. Or, you could change Iterator iterator = collection.iterator(); to

java.util.Iterator<Person> iterator = collection.iterator();

Your example did not specify the type of Iterator it should be (and your own Iterator is not generic, so if you did Iterator<Person> you would have a different error with your posted Iterator class).

点赞
评论
afuga
afuga

问题出在你的班级名字上。您已将其命名为“ Iterator”,因此编译器认为您在此处引用的是您创建的此类,而不是java.util.Iterator类。     迭代器iterator = collection.iterator(); 您可以将其更改为     java.util.Iterator iterator = collection.iterator();

或者只是重命名您创建的类(因为它是公共类,所以也要更改文件名)

点赞
评论