Java List有两个常见的子类ArrayList和LinkedList,他们都实现了AbstractList抽象类,它override了equals方法:
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof List))
return false;
ListIterator<E> e1 = listIterator();
ListIterator e2 = ((List) o).listIterator();
while(e1.hasNext() && e2.hasNext()) {
E o1 = e1.next();
Object o2 = e2.next();
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
}
return !(e1.hasNext() || e2.hasNext());
}
由上可见,List的比较是基于存储对象的equals()方法,也仅仅只跟equals()方法有关,请看例子:
import java.util.*;
public class Employee {
public String name;
public String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Employee(String name, String id){
this.name = name;
this.id = id;
}
public boolean equals(Object o){
if (this==o) return true;
if (!(o instanceof Employee)) return false;
final Employee other = (Employee)o;
if(this.name.equals(other.getName())&& this.id==other.getId())
return true;
else
return false;
}
public static void main(String[] args){
// Compare String List
List<String> l1 = new ArrayList<String>();
l1.add("A");
l1.add("B");
List<String> l2 = new ArrayList<String>();
l2.add("A");
l2.add("B");
List<String> l3 = new LinkedList<String>();
l3.add("A");
l3.add("B");
System.out.println(l1.equals(l2)); // true
System.out.println(l1.equals(l3)); // true
// Compare the Object List which doesn't have hashcode() method
List<Employee> el1 = new ArrayList<Employee>();
List<Employee> el2 = new ArrayList<Employee>();
el1.add(new Employee("Jingshou", "e523779"));
el2.add(new Employee("Jingshou", "e523779"));
System.out.println(el1.equals(el2)); // true, hashcode() is not needed
// Compare the HashSet
Set<Employee> es1 = new HashSet<Employee>();
Set<Employee> es2 = new HashSet<Employee>();
es1.add(new Employee("Jingshou", "e523779"));
es2.add(new Employee("Jingshou", "e523779"));
System.out.println(es1.equals(es2)); // false, need to override the hashcode()
}
}
结论:
- 对于List的比较,只要确保存储的对象有正确的equals()方法,直接通过list1.equals(list2)比较
- 对于存储在Hash中的对象,如果重写了equals方法,必须确保重写一个正确的hashCode()方法