import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Iterator;
interface Pet{
}
class Cat implements Pet{
public String toString(){
return "我是小猫";
}
}
class Dog implements Pet{
public String toString(){
return "我是小狗";
}
}
class Pig implements Pet{
public String toString(){
return "我是小猪";
}
}
public class MyCollection extends AbstractCollection<Pet>{
Pet pets[]={new Cat(),new Dog(),new Pig()};
public static void display(Iterator<Pet>it){
while(it.hasNext()){
Pet pet=it.next();
System.out.println(pet);
}
}
public static void display(Collection<Pet>collection){
for(Pet pet:collection){
System.out.println(pet);
}
}
public Iterator<Pet> iterator(){
return new Iterator<Pet>(){
private int index=0;
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return index<pets.length;
}
@Override
public Pet next() {
// TODO Auto-generated method stub
return pets[index++];
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
};
}
@Override
public int size() {
// TODO Auto-generated method stub
return pets.length;
}
public static void main(String[] args) {
MyCollection myCollection=new MyCollection();
Iterator<Pet>it=myCollection.iterator();
display(myCollection);
display(it);
}
}
Collection与Iterator
最新推荐文章于 2022-05-19 17:57:24 发布