Answer the question
In order to leave comments, you need to log in
Why does TreeSet count duplicate elements by HashSet key values and not by the keys themselves?
I am new to Java. I am improving my knowledge of the language on codewars.com. Performing one of the tasks, I encountered a strange thing: I want to implement a priority queue in Dijkstra's algorithm, and for time optimization I chose such a data structure as TreeSet .
import java.util.*;
public class TestTreeSet {
public static void main(String[] args) {
int[][] arr = {{1, 2, 3, 4, 5, 6}, {4, 9, 1, 2, 6, 0}};
HashMap<Integer, Integer> d = new HashMap<>();
for (int i = 0; i < arr[0].length; i++)
d.put(arr[0][i], arr[1][i]);
TreeSet<Integer> s = new TreeSet<>(new Comparator() {
public int compare(Object o1, Object o2) {
return d.get((int) o1) - d.get((int) o2);
}
});
for (int i = 1; i < 7; i++) s.add(i);
System.out.println(s); // [6, 3, 4, 1, 5, 2]
int k = 6;
if (s.contains(k)) {
s.remove(k);
d.put(k, 2);
System.out.println(s.add(k)); // false
}
System.out.println(s); // [3, 4, 1, 5, 2]
}
}
Answer the question
In order to leave comments, you need to log in
Because that's how you defined the comparator. The compare method has the following contract:
returns
d.put(k, 2);
compare(6, 3) == 0
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question