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

查看:27
本文介绍了比较 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 ) == 真

( a == b ) == true

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

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

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

我认为这是因为 contains 会检查对象引用并看到 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天全站免登陆