包含对列表
List<Pair<String, String> > lp = new ArrayList<Pair<String, String> >();
lp.add(new Pair("1", "2"));
我应该如何检查列表 lp 是否包含 1 和 2 即 Pair ("1", "2")。
List<Pair<String, String> > lp = new ArrayList<Pair<String, String> >();
lp.add(new Pair("1", "2"));
How should I check if the list lp contains 1 and 2 i.e the Pair ("1", "2").
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
Pair
类需要实现equals()
和hashCode()
并且您已准备就绪。List.contains()
是根据类型的equals()
方法实现的。请参阅List.contains()
的 API。 (编辑了一些来自 @maaartinus 的评论,你应该阅读他的答案,因为观察结果是可靠的,对我来说将它们折叠在这里有点荒谬。正如 maaartinus 指出的,这里的最佳实践是避免容易出错的 equals 和 hashcode 手动定义,而是基于 Guava 的辅助函数构建 可空等于 和 n 个对象的哈希码)。使用合适的
equals()
,您现在可以执行以下操作:回应下面的评论,也许最好包含一个很好的参考“为什么我需要实现
hashCode()?”
JavaPractices.com — 实现
equals()
—“如果覆盖 equals,则必须覆盖 hashCode”Object.equals()
合约中定义API 文档StackOverflow 答案
Your
Pair
class needs to implementequals()
andhashCode()
and you're all set.List.contains()
is implemented in terms of the type'sequals()
method. See the API forList.contains()
. (Edited a bit to address comments from @maaartinus, whose answer you should read b/c the observations are solid, and it's a bit ridiculous for me to fold them in here. As maaartinus points out, a best-practice here would be to avoid error-prone manual definitions for equals and hashcode, and instead build on Guava's helper functions for nullable equals and hashCode for n objects).With suitable
equals()
, you can now do:Responding to the comments below, perhaps it would be good to include a good reference for "Why do I need to implement
hashCode()
?"JavaPractices.com — Implementing
equals()
— "if you override equals, you must override hashCode"Object.equals()
contract as defined in the API documentationStackOverflow answer
andersoj 的答案中的实现
是错误的: null 测试清楚地表明 null 是 left 和 right 的合法值。因此,至少存在两个问题:
new Pair(null, null).hashCode()
抛出 NPEnew Pair(null, null)
不等于自身!查看 Guava 类对象以获得正确的实现。使用它或编写静态帮助器方法
,并始终使用它们。
永远不要编写包含 null 测试的
equals
。这很容易搞砸,而且没有人注意到它。使用 Helper,正确处理它很简单:
当然,在构造函数中禁止 null 也是一种选择。
The implementation in the answer by andersoj
is wrong: The null tests clearly suggest that null is a legal value for left and right. So there are at least two problems there:
new Pair(null, null).hashCode()
throws NPEnew Pair(null, null)
does NOT equal to itself!Have a look at Guava class Objects for a correct implementation. Use it or write a static helper methods like
and always use them.
Never ever write
equals
containing a null test.It's to easy to blow it, and nobody noticed it. Using the Helper, it's trivial to get it right:
Of course, forbidding nulls in the constructor is an option, too.