使用indexOf()函数时,我应该覆盖哪个函数 [英] Which function should I override when using indexOf() function
问题描述
在java中使用indexOf()函数时,我应该覆盖哪个函数。我有一个数组列表,然后我接受一个输入作为ID并创建一个包含ID的对象,所有其他元素都为null,然后我需要传递该对象并获取包含该对象的元素的索引
Which function should I override when using the indexOf() function in java. I have a array list, then I take in an input as the ID and create a object which contains the ID and all the other elements are null, then I need to pass that object and get the index of the element which contains that object
推荐答案
public boolean equals(Object o) {
if (o instanceof MyObject) {
//id comparison
MyObject mo = (MyObject)o;
return mo.id.equals(id);
}
return false;
}
将 MyObject
更改为你的班级。
请记住改变 hashCode()
以及@Hovercraft指出。 equals和hashCode一起使用(为它们读取javadoc)。否则你可能会遇到一些令人讨厌但可能很难找到的错误。
Remember to change hashCode()
as well as @Hovercraft points out. equals and hashCode go together (read the javadoc for them). Else you might run into some nasty and possibly hard to find bugs.
一个例子:
使用java 7 +你可以这样做:
With java 7+ you can do this:
public int hashCode() {
return java.util.Objects.hashCode(id);
}
这篇关于使用indexOf()函数时,我应该覆盖哪个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!