Java比较List是否相等

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()方法

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值