-
Bug
-
Resolution: Not an Issue
-
P4
-
None
-
21
-
generic
-
generic
A DESCRIPTION OF THE PROBLEM :
The documentation for add states that the set will be left unchanged if the given element is already present; however, an inspection of the source code as well as testing (see attached code) shows that adding an already present element will cause the existing element to be replaced in the set, possibly changing the order of the elements in the set.
STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
1. Add an element to a TreeSet
2. Modify the element such that the element would occupy a different position in the set if removed and added back.
3. Add the element to the set without removing first.
EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
Expected order of elements in set to remain same.
ACTUAL -
Order of elements in the set reflects new value of added element.
---------- BEGIN SOURCE ----------
import java.util.*;
public class Test {
public static void main(String[] args) {
final int[] values = {0, 1, 2};
final NavigableSet<Integer> set = new TreeSet<>((i, j) -> Integer.compare(values[i], values[j]));
set.add(0);
set.add(1);
set.add(2);
System.out.println(set.first());
values[2] = -1;
set.add(2);
System.out.println(set.first());
}
}
---------- END SOURCE ----------
The documentation for add states that the set will be left unchanged if the given element is already present; however, an inspection of the source code as well as testing (see attached code) shows that adding an already present element will cause the existing element to be replaced in the set, possibly changing the order of the elements in the set.
STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
1. Add an element to a TreeSet
2. Modify the element such that the element would occupy a different position in the set if removed and added back.
3. Add the element to the set without removing first.
EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
Expected order of elements in set to remain same.
ACTUAL -
Order of elements in the set reflects new value of added element.
---------- BEGIN SOURCE ----------
import java.util.*;
public class Test {
public static void main(String[] args) {
final int[] values = {0, 1, 2};
final NavigableSet<Integer> set = new TreeSet<>((i, j) -> Integer.compare(values[i], values[j]));
set.add(0);
set.add(1);
set.add(2);
System.out.println(set.first());
values[2] = -1;
set.add(2);
System.out.println(set.first());
}
}
---------- END SOURCE ----------