通過Iterator遍歷List


------<a href="http://www.itheima.com" target="blank">Java培訓、Android培訓</a>、期待與您交流! -------


使用Iterator 遍歷器對List集合進行遍歷


public static void main(String[] args) {

		// 1、創建多個狗狗對象
		Dog ououDog = new Dog("歐歐", "雪娜瑞");
		Dog yayaDog = new Dog("亞亞", "拉布拉多");
		Dog meimeiDog = new Dog("美美", "雪娜瑞");
		Dog feifeiDog = new Dog("菲菲", "拉布拉多");

		// 2、創建ArrayList集合對象並把多個狗狗對象放入其中
		List dogs = new ArrayList();
		dogs.add(ououDog);
		dogs.add(yayaDog);
		dogs.add(meimeiDog);
		dogs.add(2, feifeiDog);  //添加的時候,指定位置

		// 3、通過迭代器依次輸出集合中所有狗狗的信息
		System.out.println("使用Iterator遍歷,所有狗狗的暱稱和品種分別是:");
		Iterator it = dogs.iterator();  //調用集合的iterator方法
		while (it.hasNext()) {      //循環遍歷 
			Dog dog = (Dog) it.next();  //遍歷出來的對象默認是 object 類型,需要轉換  
			System.out.println(dog.getName()+"\t"+dog.getStrain());
		}
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章