java list 比较_Java比较List是否相等

Java中List的equals()方法比较依赖于存储对象的equals()方法。示例展示了即使不同类型的List(ArrayList和LinkedList)只要内容相同,equals()返回true。当比较包含自定义对象的List时,正确实现equals()就足够了。但如果是HashSet,还需要重写hashCode()以保证正确比较。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java List有两个常见的子类ArrayList和LinkedList,他们都实现了AbstractList抽象类,它override了equals方法:

public boolean equals(Object o) {

if (o == this)

return true;

if (!(o instanceof List))

return false;

ListIterator 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 l1 = new ArrayList();

l1.add("A");

l1.add("B");

List l2 = new ArrayList();

l2.add("A");

l2.add("B");

List l3 = new LinkedList();

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 el1 = new ArrayList();

List el2 = new ArrayList();

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 es1 = new HashSet();

Set es2 = new HashSet();

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值