I have an ArrayList
of a custom class Highscore
The array list contains multiple Highscore
's
As shown in the code below, there is a duplicate entry. That being, highscores.add(new Highscore("user 1", 25));
When I say duplicate, I mean the same String
(username) and int
(score) value
I want to be able to detect it so that only 1 of those entries stays in the ArrayList
Code:
ArrayList<Highscore> highscores = new ArrayList<>();
highscores.add(new Highscore("user 1", 25));
highscores.add(new Highscore("user 2", 10));
highscores.add(new Highscore("user 3", 55));
highscores.add(new Highscore("user 1", 25));
highscores.add(new Highscore("user 2", 5));
highscores.add(new Highscore("user 3", 30));
Highscore:
public class Highscore implements ConfigurationSerializable {
String username;
public int score;
public Highscore(String username, int score) {
this.username = username;
this.score = score;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> mappedObject = new LinkedHashMap<String, Object>();
mappedObject.put("username", username);
mappedObject.put("score", score);
return mappedObject;
}
public static Highscore deserialize(Map<String, Object> mappedObject) {
return new Highscore((String) mappedObject.get("username"),
(int) mappedObject.get("score"));
}
}
I have seen some people suggest using a HashSet or LinkedHashSet, but in my case, that doesn't work as it identifies duplicates based on the id of the Highscore
, which is always different.
Thanks in advance :)