ArryList类使用
ArrayListUse类:
package com.tiedandan.集合.List使用.List实现类;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class ArrayListUse {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();//创建一个数组
Student stu1 =new Student("张铁蛋",20);//new 一个student对象
Student stu2 = new Student("铁蛋蛋",19);
Student stu3 = new Student("张三",18);
arrayList.add(stu1);//添加数组元素
arrayList.add(stu2);
arrayList.add(stu3);
System.out.println(arrayList.toString());//输出数组元素,记得toString必须重写才能用.
//删除数组元素stu1
System.out.println("------------删除数组元素stu1---------------");
arrayList.remove(stu1);
//遍历数组元素.用迭代器。
System.out.println("----------------遍历数组元素.用迭代器。--------------");
Iterator it = arrayList.iterator();
while (it.hasNext()){
Student s =(Student) it.next();
System.out.println(s.toString());
}
//遍历数组元素,用列表迭代器
System.out.println("---------------遍历数组元素,用列表迭代器-------------");
ListIterator lit = arrayList.listIterator();
while (lit.hasNext()){
Student s =(Student) lit.next();
System.out.println(s.toString());
}
//遍历数组元素,用列表迭代器逆序输出
System.out.println("---------------遍历数组元素,用列表迭代器逆序输出---------------------");
while (lit.hasPrevious()){
Student s =(Student) lit.previous();
System.out.println(s.toString());
}
//判断
System.out.println(arrayList.contains(stu1));//这里把stu1删了,在比较是否含有stu1一定是false
//判断是否为空
System.out.println(arrayList.isEmpty());
//查找
System.out.println(arrayList.indexOf(stu2));
}
}
Student类:
package com.tiedandan.集合.List使用.List实现类;
public class Student {
public Student() {
}
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
[Student{name='张铁蛋', age=20}, Student{name='铁蛋蛋', age=19}, Student{name='张三', age=18}]
------------删除数组元素stu1---------------
----------------遍历数组元素.用迭代器。--------------
Student{name='铁蛋蛋', age=19}
Student{name='张三', age=18}
---------------遍历数组元素,用列表迭代器-------------
Student{name='铁蛋蛋', age=19}
Student{name='张三', age=18}
---------------遍历数组元素,用列表迭代器逆序输出---------------------
Student{name='张三', age=18}
Student{name='铁蛋蛋', age=19}
false
false
0