ArrayList集合 查詢遍歷速度快 增刪慢
阿新 • • 發佈:2021-11-13
package com.bo.collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
//ArrayList 陣列 查詢遍歷速度快 增刪慢
public class Demo05 {
public static void main(String[] args) {
//建立集合
ArrayList arrayList=new ArrayList();
//新增元素
Student s1 = new Student("趙",20);
Student s2 = new Student("錢",21);
Student s3 = new Student("孫",22);
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
System.out.println("元素個數:"+arrayList.size());
System.out.println(arrayList.toString());
//刪除元素
arrayList.remove( new Student("趙",20));//重寫返回後可以刪除
System.out.println("刪除之後:"+arrayList.size());
//遍歷元素
System.out.println("------迭代器-------");
Iterator it= arrayList.iterator();
while(it.hasNext()){
Student s=(Student)it.next();
System.out.println(s);
}
System.out.println("------列表迭代器-------");
ListIterator lit = arrayList.listIterator();
while(lit.hasNext()){
Student s=(Student)lit.next();
System.out.println(s);
}
while(lit.hasPrevious()){
System.out.println(lit.previous()+":"+lit.previousIndex());
}
//判斷
System.out.println(arrayList.contains(new Student("錢",21)));
System.out.println(arrayList.isEmpty());
//查詢
System.out.println(arrayList.indexOf(s2));
}
}