由於TreeMap排序僅基於鍵,我使用自定義對象作爲樹形圖中的鍵。我已經在我看來,尊重在此情況下,equals和的compareTo之間的合同,如果兩個對象是相等的,TE的compareTo返回0使用我自己的對象作爲TreeMap中的鍵
下面對象的代碼:
public final class UserHighScore implements Comparable<UserHighScore>{
private final int userId;
private final int value;
public UserHighScore(int userId, int value) {
this.userId = userId;
this.value = value;
}
public int getUserId() {
return userId;
}
public int getValue() {
return value;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof UserHighScore)) {
return false;
}
UserHighScore userHighScore = (UserHighScore) obj;
return userHighScore.userId==userId;
}
@Override
public int compareTo(UserHighScore uh) {
if(uh.getUserId()==this.getUserId()) return 0;
if(uh.getValue()>this.getValue()) return 1;
return -1;
}
}
而下面的方法是導致問題:
如果用戶ID是相同的我想返回0以避免重複,那麼如果我做map.put(userHighscore)它應該自動替換是否有另一個與地圖中的對象相同 用戶名。 但是,如果用戶不同,我希望他們根據他們的價值進行排序。 這種方法對於一個線程來說工作得很好,但是我的應用程序是併發的,並且當有更多的線程時,它會向地圖添加重複項。 我的問題是與高分區地圖,這是一個併發的地圖,它裏面包含一個樹形圖。
你看到我的方法有什麼問題嗎?
如果您使用多個線程,那麼您的同步策略是什麼? – vanje
您可能想要使用併發包中的映射https://docs.oracle.com/javase/tutorial/essential/concurrency/collections.html –
已經這樣做了。我已經編輯了問題以顯示代碼,我正在使用concurrentHashmap – fgonzalez