比较LinkedList.contains()中的对象 [英] Compare objects in LinkedList.contains()

查看:88
本文介绍了比较LinkedList.contains()中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够让LinkedList.contains()为自定义比较器返回true。

I want to be able to have LinkedList.contains() return true for a custom comparator.

假设我有1个LinkedList和2个对象

Suppose that I have 1 LinkedList and 2 objects

LinkedList<MyObject> myList = new LinkedList<MyObject>();

MyObject a = new MyObject("HELLO");
MyObject b = new MyObject("HELLO");

技术上,两个对象在比较方面是相同的(MyObject实现Comparable)

Technicaly, both objects are identical in terms of comparison (MyObject implements Comparable)

(a == b)== true

( a == b ) == true

但是,当我执行以下操作时,对于myList.contains,myList不会返回true (b)

however, when I do the following, myList does not return true for myList.contains(b)

myList.add(a)
myList.contains(b) // == false

我认为它包含将检查对象引用,并看到a和b是2个不同的对象。
我有什么方法可以做到这一点所以我不必扩展LinkedList来比较这些对象吗?

I think its because contains will check object reference and see that a and b are 2 distinct objects. Is there any way I can make it so I don't have to extend LinkedList to compare those objects?

推荐答案

LinkedList使用equals方法,而不是Comparable.compareTo。您应该在MyObject中覆盖equals(和hashCode)来解决问题。

LinkedList uses the equals method, not Comparable.compareTo. You should override equals (and hashCode) in MyObject to solve the problem.

这篇关于比较LinkedList.contains()中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆