我有一个任务,包括模式实现(Iterator)和在先前创建的类Hotel和Tours中添加方法iterator()。不幸的是,我还是Java的新手,所以我不知道如何使用IIterator中的方法来进行arraylist inter。信息 - 界面
public class IIterator<T> implements Iterator<T> {
private Object elements;
int index = 0;
public boolean hasNext() {
return index< Array.getLength(elements);
}
public T next() {
return (T) Array.get(elements, index++);
}
public void remove() {
throw new UnsupportedOperationException("remove");
}
}
public class Hotel implements Info, Serializable, Cloneable, Comparable{
public Iterator iterator() {
return new IIterator();
}
}
public class Tours implements Info, Serializable, Cloneable, Comparable{
public Iterator iterator() {
return new IIterator();
}
}
ArrayList<Info> inter = new ArrayList();
inter.add(new Hotel("Lara", 100, 5));
inter.add(new Hotel("Katya", 10, 1));
inter.add(new Tours("Lara", 1000, length));
inter.add(new Tours("HelsinkiPanorama", 1010, length));
答案 0 :(得分:1)
<强> EDITED 强>
你可以这样做:
for (Info info : inter) {
System.out.println(info.getString());
}
或
Iterator<Info> it = inter.iterator();
while (it.hasNext()){
System.out.println(it.next().getString());
}
上一个回答
我不确定你的问题,但如果你想要一个简单的迭代器示例,你可以看到:
public class Hotel {
private String name;
public Hotel(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class Tours implements Iterable<Hotel>{
private List<Hotel> hotels = new ArrayList<>();
public void addHotel(Hotel hotel){
hotels.add(hotel);
}
@Override
public Iterator<Hotel> iterator() {
return hotels.iterator();
}
}
示例:
public static void main(String[] args) {
Tours tours = new Tours();
tours.addHotel(new Hotel("hotel-0"));
tours.addHotel(new Hotel("hotel-1"));
tours.addHotel(new Hotel("hotel-2"));
tours.addHotel(new Hotel("hotel-3"));
for (Hotel hotel : tours) {
System.out.println(hotel.getName());
}
}
打印:
hotel-0
hotel-1
hotel-2
hotel-3
如果你想在引擎盖下看到一个例子
public class Tours implements Iterable<Hotel>{
private int numHotels = 0;
private Hotel[] hotels = null;
public void addHotel(Hotel hotel){
if (hotels == null){
hotels = new Hotel[5];
} else if ( numHotels + 1 >= hotels.length){
hotels = Arrays.copyOf(hotels, numHotels + 5);
}
hotels[numHotels++] = hotel;
}
@Override
public Iterator<Hotel> iterator() {
return new HotelIterator();
}
private class HotelIterator implements Iterator<Hotel> {
private int index = 0;
@Override
public boolean hasNext() {
return index < numHotels;
}
@Override
public Hotel next() {
return hotels[index++];
}
}
}
示例2:
public static void main(String[] args) {
Tours tours = new Tours();
tours.addHotel(new Hotel("hotel-0"));
tours.addHotel(new Hotel("hotel-1"));
tours.addHotel(new Hotel("hotel-2"));
tours.addHotel(new Hotel("hotel-3"));
for (Hotel hotel : tours) {
System.out.println(hotel.getName());
}
}
打印:
hotel-0
hotel-1
hotel-2
hotel-3