import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class ArrayListTest {
public static void main(String[] args) {
student s1 =new student("惶惶",21);
student s2 =new student("人世",21);
student s3 =new student("不可推磨",21);
ArrayList arrayList =new ArrayList();
System.out.println("---------添加元素----------");
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
System.out.println(arrayList);
System.out.println("---------遍历元素----------");
System.out.println("---------普通迭代器遍历----------");
Iterator iterator =arrayList.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("---------列表迭代器遍历----------");
ListIterator listIterator =arrayList.listIterator();
System.out.println("逆序:");
for (;listIterator.hasNext();) {
listIterator.next();
}
while (listIterator.hasPrevious()){
System.out.println(listIterator.previous());
}
System.out.println("顺序:");
while (listIterator.hasNext()){
System.out.println(listIterator.next());
}
System.out.println("---------判断----------");
System.out.println("是否包含对象s1:"+arrayList.contains(s1));
System.out.println("是否包含对象(人世,21):"+arrayList.contains(new student("人世",21)));
System.out.println("集合是否为空:"+arrayList.isEmpty());
System.out.println("---------查找----------");
System.out.println(arrayList.indexOf(s1));
System.out.println(arrayList.indexOf(new student("不可推磨",21)));
System.out.println("---------删除元素----------");
arrayList.remove(new student("惶惶",21));
System.out.println(arrayList);
}
}
输出结果:
---------添加元素----------
[student[name='惶惶', age=21], student[name='人世', age=21], student[name='不可推磨', age=21]]
---------遍历元素----------
---------普通迭代器遍历----------
student[name='惶惶', age=21]
student[name='人世', age=21]
student[name='不可推磨', age=21]
---------列表迭代器遍历----------
逆序:
student[name='不可推磨', age=21]
student[name='人世', age=21]
student[name='惶惶', age=21]
顺序:
student[name='惶惶', age=21]
student[name='人世', age=21]
student[name='不可推磨', age=21]
---------判断----------
是否包含对象s1:true
是否包含对象(人世,21):true
集合是否为空:false
---------查找----------
0
2
---------删除元素----------
[student[name='人世', age=21], student[name='不可推磨', age=21]]