本文介紹了我可以讓indexOf以不同的方式比較對象嗎?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想使用indexOf
,但List
中的對象將不是相等的對象,但它們將具有值相等(即。它們相等但不相等)。
我想以與Object.equals
方法不同的方式進行indexOf
比較。我在考慮重寫equals方法以改用我的IsEvalence方法,但我不確定如何做到這一點,如果可能的話。
我嘗試了很多版本,但一直收到錯誤:
List<CustomType> items{
@Override
public boolean equals(Object o)
{
return false;
}
}
= //stuff to populate it
我也見過this answer他們談論EqualityCompeller‘s,Java中有類似的東西嗎?
還是有其他方法可以實現這一點?
推薦答案
這是我對它的嘗試。我使用ArrayList
是因為List是一個接口,您需要覆蓋所有方法。
List<CustomType> customList = new ArrayList<CustomType>() {
@Override
public int indexOf(Object o) {
if (o instanceof CustomType) {
for (int i = 0; i < this.size(); i++) {
CustomType c = (CustomType) o;
if (c.isEquivalent(this.get(i))) {
return i;
}
}
}
return -1;
}
};
// use indexOf like normal, but beware of side-effects as mentioned in the comments
或者
我在前面的評論中想說的是,如果您覆蓋List.equals
,這意味著您正在將List
對象與另一個對象進行比較,而不是列表中的對象。要做你要求的事情,你需要這樣做。
class CustomType {
public boolean isEquivalent(CustomType ct) {
return true; // TODO: Implement this
}
@Override
public boolean equals(Object obj) {
// TODO: Implement this
if (obj instanceof CustomType) {
return this.isEquivalent((CustomType) obj);
}
return false;
}
@Override
public int hashCode() {
return super.hashCode(); // TODO: Implement this
}
}
public static void main(String args[]) {
List<CustomType> lst = new ArrayList<CustomType>();
// use indexOf like normal
}
這篇關于我可以讓indexOf以不同的方式比較對象嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,