集合類的2種遍歷方法加上如何遍歷自定義物件
阿新 • • 發佈:2019-01-27
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
class Cat{
String name;
int age;
Cat(String name,int age){
this.name = name;
this.age = age;
}
void show(){
System.out.println(this.name+this.age);
}
}
@SuppressWarnings ("unchecked")
public class TEST {
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
Collection c = new ArrayList();
c.add("a");
c.add("b");
c.add("c");
//1.集合變成陣列再進行遍歷
Object[] arr = c.toArray();
for (int i=0;i<arr.length;i++) {
System.out .println(arr[i]);
}
System.out.println("-----------------");
//2.迭代器遍歷
Iterator it = c.iterator();
while(it.hasNext()){//判斷有沒有元素
System.out.println(it.next());//取元素
}
System.out.println("-----------------");
//3.遍歷自定義物件
Collection c1 = new ArrayList();
c1.add(new Cat ("小花",1));
c1.add(new Cat ("大白",5));
Iterator it1 = c1.iterator();//裡面的物件都會自動提升為Object類
while(it1.hasNext()){
Cat cat = (Cat)it1.next();
cat.show();
}
}
}