Here is my collection. Here I try to make my own implemetation with special Comparator that sorts Integer elements by its absolute values.
class SortedByAbsoluteValueIntegerSet extends TreeSet {
private TreeSet<Integer> mySet;
public SortedByAbsoluteValueIntegerSet() {
mySet = new TreeSet<Integer>(Comparator.comparing(Math::abs));
}
@Override
public boolean add(Object o) {
mySet.add((Integer) o);
return true;
}
@Override
public boolean addAll(Collection c) {
for (Object o : c) {
mySet.add((Integer) o);
}
return true;
}
public Iterator<Integer> iterator() {
return mySet.iterator();
}
(and other methods)
Main class. Everything seems to work correct except toString() method. When I overwrite this method without lambdas it works. But! This method is in tests and I mustn’t change it. I just copied it to Main class trying to understand the problem. And problem I want to solve is somewhere in SortedByAbsoluteValueIntegerSet class.
public static void main(String[] args) {
Set<Integer> set = new SortedByAbsoluteValueIntegerSet();
Arrays.asList(1, 3, 5, 7, 9).forEach(set::add);
set.addAll(Arrays.asList(-2, -4, -6, -8, -10));
System.out.println("set.size() = " + set.size()); //OUTPUT:"set.size() = 10"
System.out.println("set = " + set); //OUTPUT:"set = [-10, -8, -6, -4, -2, 1, 3, 5, 7, 9]"
System.out.println("toString(set) = " + toString(set)); //OUTPUT:"toString(set) = "
}
private static String toString(final Collection<Integer> collection) {
return String.join(" ", collection.stream()
.map(i -> Integer.toString(i))
.toArray(String[]::new));
}
This is another realization that works good. So what’s the difference?
private static String toString(final Collection<Integer> collection) {
List<String> list = new ArrayList<>();
for (Integer i : collection) {
String s = Integer.toString(i);
list.add(s);
}
return String.join(" ", list.toArray(new String[0]));
}
Advertisement
Answer
You shouldn’t be extending TreeSet and having a TreeSet
field. One or the other, but both makes no sense.
This is probably actually the cause of your issue: you have two different TreeSet
s associated with each SortedByAbsoluteValueIntegerSet
, and the one you’re adding to and the one toString()
is getting are different.
Extend AbstractSet
instead.