Collection集合元素的通用獲取方式:在取元素之前先要判斷集合中有沒有元素,如果有,就把這個元素取出來,繼續判斷,如果還有就再取出來。一直把集合中的元素全部取出。這種取出方式專業術語稱爲迭代。
集合中把這種取元素的方式描述在Iterator接口中。Iterator接口的常用方法:
迭代器的代碼實現:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class IteratorDemo {
public static void main(String[] args) {
Collection<String> coll = new ArrayList<String>();
coll.add("abc1");
coll.add("abc2");
coll.add("abc3");
coll.add("abc4");
//迭代器,對集合ArrayList中的元素進行取出
Iterator<String> it = coll.iterator();
while(it.hasNext()){
String s = it.next();
System.out.println(s);
}
迭代集合元素圖解:
集合元素的向下轉型
集合中可以存儲任何對象,但是存放進去的數據提升成了Object。集合中存儲其實都是對象的地址。基本類型包裝類提供了自動裝箱操作(基本類型->對象),這樣,集合中的元素就是基本類型的包裝類對象。存儲時提升了Object,取出時要使用元素的特有內容,必須向下轉型。
Collection coll = new ArrayList(); coll.add("abc"); coll.add("aabbc"); coll.add("abctest"); Iterator it = coll.iterator(); while (it.hasNext()){ //向下轉型 String str = (String)it.next(); System.out.println(str.length()); }
注意:如果集合中存放的是多個對象,這時進行向下轉型會發生類型轉換異常。
Iterator接口也可以使用<>來控制迭代元素的類型
Collection<String> coll = new ArrayList<String>(); coll.add("abc"); coll.add("aabbc"); coll.add("abctest"); Iterator<String> it = coll.iterator(); while (it.hasNext()){ String str = it.next(); //當使用Iterator<String>控制元素類型後,就不需要強轉了。獲取到的元素直接就是String類型 System.out.println(str.length()); }
增強for循環 專門用來遍歷數組和集合的,它的內部原理其實是個 Iterator迭代器,所以在遍歷的過程中,不能對集合中的元素進行增刪操作。
格式:for(元素的數據類型 變量 : Collection集合or數組){}
代碼實現:
public class ForEachDemo {
public static void main(String[] args) {
function();
}
/*
* 實現for循環,遍歷數組
* 好處: 代碼少了,方便對容器遍歷
* 弊端: 沒有索引,不能操作容器裏面的元素
*/
public static void function(){
int[] arr = {3,1,9,0};
for(int i : arr){
System.out.println(i+1);
}
System.out.println(arr[0]);
}
}
for對於對象數組遍歷的時候,也是可以調用對象的方法的
public class ForEachDemo {
public static void main(String[] args) {
function_1();
}
public static void function_1(){
String[] str = {"abc","itcast","cn"};
for(String s : str){
System.out.println(s.length());
}
}
}
增強for循環遍歷集合:
import java.util.ArrayList;
import demo.Person; //已經寫過的demo包中Person類
public class ForEachDemo {
public static void main(String[] args) {
function_2();
}
/*
* 增強for循環遍歷集合
* 存儲自定義Person類型
*/
public static void function_2(){
ArrayList<Person> array = new ArrayList<Person>();
array.add(new Person("a",20));
array.add(new Person("b",10));
for(Person p : array){
System.out.println(p);
}
}