【发布时间】:2023-03-29 03:49:01
【问题描述】:
我正在尝试在 OOP 中学习不同的设计模式,而我目前正在学习的是迭代器模式。因此我制作了两个自己的接口(Iterable 和 Iterator)。
我正在尝试迭代 List<Person> friends。但是行:for (Person p : p1) 给出以下编译器错误:
foreach not applicable to type 'com.company.Person'
这对我来说毫无意义,因为我已经实现了 Iterable 并在我所见的范围内覆盖了 iterator() 方法。
谁能告诉我我错过了什么?
这是我的代码:
主类:
Person p1 = new Person("Erik");
p1.addFriend("Lars");
p1.addFriend("Jenny");
p1.addFriend("Janne");
for (Person p : p1) {
System.out.println(p.name);
}
迭代器:
public interface Iterator<T> {
boolean hasNext();
T next();
void remove();
}
可迭代:
public interface Iterable<T> {
Iterator<T> iterator();
}
人:
public class Person implements Iterable<Person>{
private List<Person> friends = new ArrayList<>();
String name;
int index = 0;
public Person(String name){
this.name = name;
}
public void addFriend(String name){
friends.add(new Person(name));
}
@Override
public Iterator<Person> iterator(){
return new Iterator<Person>() {
//int index = 0;
@Override
public boolean hasNext() {
System.out.println(index);
return index < friends.size();
}
@Override
public Person next() {
if(hasNext()){
return friends.get(index++);
}
else{
return null;
}
}
@Override
public void remove() {
if(index<=0) {
friends.remove(index--);
}
}
};
}
}
【问题讨论】:
-
好像您创建了自己的
Iterable<...>界面? foreach 仅适用于java.lang.Iterable。 -
另外,
Person是不可迭代的。Person的集合是。如果您已经拥有Person的集合(就像您所做的那样),那么您应该已经能够迭代该集合。 -
换句话说,它应该是
for (Person p : friends) { // do something with p },读作“对于你的friends集合中的每个Person p,用p做一些事情”
标签: java design-patterns foreach iterator iterable