[英]Pattern iterator
我有一个任务,包括模式实现(Iterator)和在先前创建的Hotel and 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));
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.