首先上代碼:java
import java.util.*; interface Pet{ // 定義寵物接口 public String getName() ; public String getColor() ; public int getAge() ; } class Cat implements Pet{ // 貓是寵物,實現接口 private String name ; // 寵物名字 private String color ; // 寵物顏色 private int age ; // 寵物年齡 public Cat(String name,String color,int age){ this.setName(name) ; this.setColor(color) ; this.setAge(age) ; } public void setName(String name){ this.name = name ; } public void setColor(String color){ this.color = color; } public void setAge(int age){ this.age = age ; } public String getName(){ return this.name ; } public String getColor(){ return this.color ; } public int getAge(){ return this.age ; } }; class Dog implements Pet{ // 狗是寵物,實現接口 private String name ; // 寵物名字 private String color ; // 寵物顏色 private int age ; // 寵物年齡 public Dog(String name,String color,int age){ this.setName(name) ; this.setColor(color) ; this.setAge(age) ; } public void setName(String name){ this.name = name ; } public void setColor(String color){ this.color = color; } public void setAge(int age){ this.age = age ; } public String getName(){ return this.name ; } public String getColor(){ return this.color ; } public int getAge(){ return this.age ; } }; class PetShop{ // 寵物商店 private Pet[] pets ; // 保存一組寵物 private int foot ; public PetShop(int len){ if(len>0){ this.pets = new Pet[len] ; // 開闢數組大小 }else{ this.pets = new Pet[1] ; // 至少開闢一個空間 } } public boolean add(Pet pet){ // 增長的是一個寵物 if(this.foot<this.pets.length){ this.pets[this.foot] = pet ; // 增長寵物 this.foot ++ ; return true ; }else{ return false ; } } public ArrayList<Pet> search(String keyWord){ ArrayList<Pet> pet=new ArrayList<Pet>(); for(int i=0;i<this.pets.length;i++){ if(this.pets[i]!=null){ // 表示此位置有寵物 if(this.pets[i].getName().indexOf(keyWord)!=-1 ||this.pets[i].getColor().indexOf(keyWord)!=-1){ pet.add(this.pets[i]); } } } return pet ; } }; public class PetShopDemo_1{ public static void main(String args[]){ PetShop ps = new PetShop(5) ; // 五個寵物 ps.add(new Cat("白貓","白色的",2)) ; // 增長寵物,成功 ps.add(new Cat("黑貓","黑色的",3)) ; // 增長寵物,成功 ps.add(new Cat("花貓","花色的",3)) ; // 增長寵物,成功 ps.add(new Dog("拉步拉多","黃色的",3)) ; // 增長寵物,成功 ps.add(new Dog("金毛","金色的",2)) ; // 增長寵物,成功 ps.add(new Dog("黃狗","黑色的",2)) ; // 增長寵物,失敗 print(ps.search("貓")) ; } public static void print(ArrayList<Pet> pet){ for(int i=0;i<pet.size();i++) { System.out.println(pet.get(i).getName()); } } };
問題出在後面搜索結果的遍歷上面:數組
這種方法正確,能夠取得結果this
public static void print(ArrayList<Pet> pet){ for(int i=0;i<pet.size();i++) { System.out.println(pet.get(i).getName()); } }
而是用迭代器的這種方法卻無論用spa
public static void print(ArrayList<Pet> pet){ Iterator it1=pet.iterator(); while(it1.hasNext()) { System.out.println(it1.next().getName()); } }
報錯,表示找不到getName(),可是直接輸出it1.next()的結果和上面直接輸出p[i]的結果是同樣的,說明下面一種方法也是能夠取得對象的地址的,至於爲何找不到getName()code
方法,則就不明白了。個人想法是,It1已經轉化成迭代器了,迭代器只能看到對象,看不到裏面的東西。對象
由於it1.next()得到的是迭代器裏面的內容。blog