patternjavaModerate
Comparing list elements in an effective way
Viewed 0 times
comparingelementswaylisteffective
Problem
I have a list of opened nodes, with each step about 3000 nodes are opened and I want to put to the opened list only those nodes that are not already there. For now I'm just comparing each new one to all of the ones already in the opened list and only add it if it's not there. But that is around n*3000^2 comparisons for the nth step and makes the progress slower and slower each step. Is there a way to do it faster. Or at least is there a structure that would be better than ArrayList.
This is part of the bigger code, but basically the method I use:
As for the isSame() method from the gameState class, it just returns true when the two gameStates are considered the same.
This is part of the bigger code, but basically the method I use:
public void addEverything() {
List list = current.neighbours;
for (gameState state : list) {
if (!isOpened(state)) {
opened.add(state);
}
}
}
public boolean isOpened(gameState state) {
for (int i = 0; i < opened.size(); i++) {
if (state.isSame(opened.get(i)))
return true;
}
return false;
}As for the isSame() method from the gameState class, it just returns true when the two gameStates are considered the same.
Solution
-
Instead of implementing
If you need a list, you can convert it back after the loop:
See also: Overriding equals and hashCode in Java
-
According to the Java Code Conventions, class names in Java usually starts with uppercase letters.
Instead of implementing
isSame implement equals and hashCode. After that you could use a HashSet (or LinkedHashSet if the order of elements is important). Set is a collection that contains no duplicate elements and inserting/searching is much faster than searching in a list.Set opened = new LinkedHashSet();
public void addEverything() {
List list = current.neighbours;
for (GameState state : list) {
opened.add(state);
}
}If you need a list, you can convert it back after the loop:
List openedList = new ArrayList(opened);See also: Overriding equals and hashCode in Java
-
According to the Java Code Conventions, class names in Java usually starts with uppercase letters.
Code Snippets
Set<GameState> opened = new LinkedHashSet<GameState>();
public void addEverything() {
List<GameState> list = current.neighbours;
for (GameState state : list) {
opened.add(state);
}
}List<GameState> openedList = new ArrayList<GameState>(opened);Context
StackExchange Code Review Q#44662, answer score: 17
Revisions (0)
No revisions yet.