?? arraylisttest.java
字號:
package util;
import java.util.*;
/*
* ArrayList數組實現了List接口,而List接口提供了根接口Collection不具備的get(int index)
* 方法獲取指定元素.又因為List是Collection派生而來的.故ArrayList方法能通過get(int index)方法獲取數組中的元素.
* Collection 接口提供了size()方法.由于Collection接口提供了iterator()方法,它返回Iterator對象,因此繼承Collection
* 的接口和間接實現Collection的類都具有這個方法.都可以使用Iterator來獲取數組元素.由于Arrays.asList()返回一個List列表.
*
*/
public class ArrayListTest {
public static void printElements(Collection c){//迭代器提供了一種通用的方式支訪問集合中的元素
Iterator it=c.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
public static void main(String[] args) {
ArrayList al=new ArrayList();
al.add(new Student(20,"winsun"));
al.add(new Student(19,"weixin"));
al.add(new Student(18,"mybole"));
for(int i=0;i<al.size();i++)
System.out.println(al.get(i));//通過索引的方式獲取對象數組的元素.
System.out.println(al);//輸出對象,則調用對象默認的toString()方法,
//然后它調用在列表當中元素的toString()方法,將元素打印輸出.可以重寫這個方法.
System.out.println("------------------------------------------------");
Object objs[]=al.toArray();//toArray()方法返回的是一個對象類型的數組.
for(int i=0;i<objs.length;i++)
System.out.println(objs[i]);//調用toString()方法.
System.out.println("-----------");
List l=Arrays.asList(objs);//注意,Arrys類中的asList方法不支持Iterator中的remove()方法.將一個對象數組轉換為列表返回,
//這個列表為固定的尺寸即大寫不可修改,返回類型為List接口.
/* Arrays.asList()方法與Collection.toArray()方法,作為數組與集合類的橋.也就是說我們想要從集合類當中獲取一個數組就
* 使用toArray()方法.如果想要從數組中獲取列表,就使用asList()方法.
*/
System.out.println(l);
System.out.println("------------------------------------------------");
Iterator it=al.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
System.out.println("------------");
//有一些集合類沒有提供get()方法來獲取集合中的元素.那么些就可以通過返回一個Iterator,
//然后迭代集合中的元素.更重要的作用是提供了一種通用的方式支訪問集合中的元素.
printElements(al);//Iterator提供了一種通用的方式支訪問集合中的元素.
System.out.println("------------");
}
}
class Student{
int age;
String name;
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public String toString(){
return "name= "+name+" age= "+age;
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -