简体   繁体   English

Java ArrayList接口类型

[英]Java ArrayList Interface Type

I have many classes that implement a common interface. 我有许多实现通用接口的类。 I use a definition like Array List mytypes, and add objects of that type to the ArrayList. 我使用类似“数组列表” mytypes的定义,并将该类型的对象添加到ArrayList中。 Now i want to use contains method of the ArrayList class to see if this List contains a class i am adding. 现在,我想使用ArrayList类的contains方法来查看此List是否包含我要添加的类。

If I implement hashcode and equals on the classes will the contains method know if a certain object already is in the ArrayList or not? 如果我在类上实现hashcode和均equals ,contains方法是否会知道某个对象是否已经在ArrayList中?

from List.contains() : List.contains()

Returns true if this list contains the specified element. 如果此列表包含指定的元素,则返回true。 More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)). 更正式地讲,当且仅当此列表包含至少一个元素(e == null?e == null:o.equals(e))时,返回true。

So basically hashCode() is not relevant here, only equals() 所以基本上hashCode()在这里不相关,只有equals()

EDIT : [better explicit then implicit], as mentioned in comments by @aiobee, equals() still needs to be overriden - according to the contract - but it will not have effect on the value returned by contains() 编辑 :[更好的显式然后隐式的],如@aiobee的注释中所述,根据合同, equals()仍需要被覆盖-但不会对contains()返回的值产生影响

Implementing hashCode is not useful for that purpose but it is a goog practice to override both equals and hashCode simultaneously. 为此,实现hashCode没什么用,但是同时覆盖equals和hashCode是一种愚蠢的做法。

Yes, it will work, that is the purpose of the contains method. 是的,它将起作用,这就是contains方法的目的。

ArrayList.contains won't use hashCode , but it will use equals , as documented : ArrayList.contains将不使用hashCode ,但将使用equals如记录所示

Returns true if this list contains the specified element. 如果此列表包含指定的元素,则返回true。 More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)). 更正式地讲,当且仅当此列表包含至少一个元素(e == null?e == null:o.equals(e))时,返回true。

(This won't check whether "this class" is already in the list - it will check whether an equal object is in the list.) (这不会检查列表中是否已经存在“此类”,它将检查列表中是否存在相等的对象 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM