import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class Demo01 {
public static void main(String[] args) {
//ArrayList的使用
//存储结构:数组,查询快,增删慢
/*
ArrayList源码分析
DEFAULT_CAPACITY=10 默认容量
注意:如果没有向集合中添加任何元素时,容量为0,添加一个元素后,容量为10;容量超过10后,容量会扩容,每次扩容大小时原来的1.5倍
elemenData 存放元素的数组
size 实际的元素个数
add(); 添加元素
*/
//创建集合
ArrayList arrayList = new ArrayList<>();
//1.添加元素
Student s1 = new Student("张三", 16);
Student s2 = new Student("李四", 16);
Student s3 = new Student("王五", 16);
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
System.out.println("元素个数:"+arrayList.size());//元素个数:3
System.out.println(arrayList);//[Student{name='张三', age=16}, Student{name='李四', age=16}, Student{name='王五', age=16}]
//2.删除元素
//arrayList.remove(0);
//arrayList.remove(s1);
arrayList.remove(new Student("张三", 16));
System.out.println("元素个数:"+arrayList.size());//元素个数:2
System.out.println(arrayList);//[Student{name='李四', age=16}, Student{name='王五', age=16}]
//3.遍历元素
//1.使用迭代器
Iterator iterator = arrayList.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
//2.列表迭代器
ListIterator listIterator = arrayList.listIterator();
//从前往后
while (listIterator.hasNext()){
System.out.println(listIterator.next());
}
//从后往前
while (listIterator.hasPrevious()){
System.out.println(listIterator.previous());
}
//4.判断
System.out.println(arrayList.contains(new Student("彭于晏",24)));//false
System.out.println(arrayList.contains(new Student("李四",16)));//true
System.out.println(arrayList.isEmpty());//false
//5.查找
System.out.println(arrayList.indexOf(s3));//1
}
}
public class Student {标签:name,ArrayList,List,System,----,age,Student,println,arrayList From: https://www.cnblogs.com/123456dh/p/17133074.html
private String name;
private int age;
public Student() {
}
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object obj) {
//1.判断是否为空
if(obj==null){
return false;
}
//2.判断是否为同一个对象
if(obj==this){
return true;
}
//判断是否可转为Student类型
if(obj instanceof Student){
Student s=(Student) obj;//强转
if(this.name.equals(s.getName())&&this.age==s.getAge()){
return true;
}
}
return false;
}
}