package ListDemo;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/*
当我们调用无参构造方法来构造一个ArrayList对象的时候,
它会在内部分配一个初始大小为10的一个Object类型的数组。
当添加的数据容量超过数组大小的时候,
会产生一个新的数组,新数组的大小为原来数组大小的1.5倍,
接着原数组中的数据拷贝到新数组。
*/
public class ArrayListDemo {
public static void main(String[] args) {
List<Student> arrayList = new ArrayList<>();
Student stu1=new Student("zhangsan",10);
Student stu2=new Student("huangsan",20);
Student stu3=new Student("yangsan",30);
Student stu4=new Student("mandysan",30);
Student stu5=new Student("marysan",40);
arrayList.add(stu1);
arrayList.add(stu2);
arrayList.add(stu3);
arrayList.add(stu4);
arrayList.add(stu5);
Student stu6=new Student("zhangsan",10);
System.out.println(arrayList.indexOf(stu6));//没有添加stu6,所以找不到
//重写equals方法,就可以找到stu6,只要name和age一样,就可以
System.out.println(arrayList.contains(stu6));//true,也用到了重写的equald()方法,只要name和age一样,就可以
System.out.println(arrayList.remove(stu6));//true,实际是把stu1删掉了,也用到了重写的equald()方法
System.out.println(arrayList.indexOf(stu1));//-1,找不到了
System.out.println(arrayList.size());//4
}
}
class Student{
private String name;
private int 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;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;//自己跟自己比,返回true
if (!(o instanceof Student)) return false;//类型不一样,返回false
Student student = (Student) o;
return getAge() == student.getAge() &&
getName().equals(student.getName());//只有名字和年龄一样,才返回true
}
@Override
public int hashCode() {
return Objects.hash(getName(), getAge());
}
}
Java:ArrayListDemo学习2020.3.5
最新推荐文章于 2021-08-07 21:13:18 发布
本文深入探讨了Java中ArrayList的动态扩容机制,当添加的数据超过初始容量时,ArrayList如何自动调整其内部数组的大小。此外,通过一个学生对象列表的例子,详细解释了equals和hashCode方法的重写对ArrayList中对象比较的影响。

138

被折叠的 条评论
为什么被折叠?



