标签:java
学习内容:
List长度可变,可存储重复值,可以存储null;
ArrayList,使用数组实现,增删性能差,查询快;LinkedList,使用链表实现,增删快,查询慢。
-------------------------------------------------------------
作业:重写equals
public class CollectionDemo {
public static void main(String[] args) {
Student s1 = new Student("tom", 12, 1);
Student s2 = new Student("tom1", 12, 1);
Student s3 = new Student("tom", 12, 1);
System.out.println(s1 == s2);
System.out.println(s1.equals(s3));
System.out.println();
List<Student> ss = new ArrayList<>();
for (int i = 0; i < 100; i++) {
ss.add(new Student("tom" + i, i, i % 2 == 0 ? 0 : 1));
}
System.out.println(ss.contains(new Student("tom10",10,0)));
System.out.println(ss.remove(new Student("tom10",10,0)));
System.out.println(ss.contains(new Student("tom10",10,0)));
}
}
class Student {
private String name;
private int age;
private int sex;
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 int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public Student(String name, int age, int sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
if (obj.getClass() == Student.class) {
Student student = (Student) obj;
if (this.getName() != null) {
if (this.getName().equals(student.getName())) {
if (this.getAge() == student.getAge()) {
if (this.getSex() == student.getSex()) {
return true;
}
}
}
} else {
if (student.getName() == null) {
if (this.getAge() == student.getAge() && this.getSex() == student.getSex()) {
return true;
}
}
}
}
return false;
}
}这样可以判断,list在调用contains(obj),remove(obj)等方法时,都会调用equal()来判断集合中是否存在这个对象
标签:java
原文地址:http://11312010.blog.51cto.com/11302010/1782419