對於企業原因我不能覆蓋hashCode
,我必須使用Java 6(但我可以用番石榴)刪除重複沒有覆蓋的hashCode()
請告訴我最好成績/簡單/快捷/最有效的/ [插入不確定的形容詞相當於最好的]機制從Java集合中刪除重複的bean?
重複由返回相同值的getter子集定義,例如,
pojoA.getVal() == pojoB.getVal() && pojoA.getOtherVal() == pojoB.getOtherVal()
對於企業原因我不能覆蓋hashCode
,我必須使用Java 6(但我可以用番石榴)刪除重複沒有覆蓋的hashCode()
請告訴我最好成績/簡單/快捷/最有效的/ [插入不確定的形容詞相當於最好的]機制從Java集合中刪除重複的bean?
重複由返回相同值的getter子集定義,例如,
pojoA.getVal() == pojoB.getVal() && pojoA.getOtherVal() == pojoB.getOtherVal()
裹的利益爲自己的類的對象,並覆蓋其hashCode
/equals
要注意屬性的特定子集。製作一個包裝器的散列集合,然後從集合中收集對象以獲得無重複的子集。
下面是一個例子:
class ActualData {
public String getAttr1();
public String getAttr2();
public String getAttr3();
public String getAttr4();
}
比方說,你要注意的屬性1,2,4,然後你就可以像這樣的包裝:
class Wrapper {
private final ActualData data;
public ActualData getData() {
return data;
}
private final int hash;
public Wrapper(ActualData data) {
this.data = data;
this.has = ... // Compute hash based on data's attr1, 2, and 4
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Wrapper)) return false;
Wrapper other = (Wrapper)obj;
return data.getAttr1().equals(other.getAttr1())
&& data.getAttr2().equals(other.getAttr2())
&& data.getAttr4().equals(other.getAttr4());
}
}
現在你可以做一個HashSet<Wrapper>
:
Set<Wrapper> set = new HashSet<>();
for (ActualData item : listWithDuplicates) {
if (!set.add(new Wrapper(item))) {
System.out.println("Item "+item+" was a duplicate");
}
}
你可以使用一個new TreeSet<Pojo> (comparator)
有比較IM以滿足你的條件(假設整數在這裏,但根據需要替換 - 對於不可比較的對象,你需要找到一個返回一些整數的黑客)。
if (pojoA.getVal() != pojoB.getVal())
return Integer.compare(pojoA.getVal(), pojoB.getVal());
if (pojoA.getOtherVal() != pojoB.getOtherVal())
return Integer.compare(pojoA.getOtherVal(), pojoB.getOtherVal());
return 0;
雖然不像純HashSet那樣高效,但@dasblikenlight的建議可能會更好。
我對,目前的hashCode沒有反映任何關於getter返回值的等號?它是如何實現的? – sphinks
@sphinks是hashcode是事實上的對象 – NimChimpsky
寫一個比較器? –