5

The NavigableSet.lower(E) Javadoc says it returns the greatest element in this set strictly less than the given element, or null if there is no such element. Why is 1 the output here? Shouldn't it be 4?

NavigableSet original = new TreeSet();
original.add("1");
original.add("2");
original.add("3");
original.add("4");
original.add("10");
Object lower = original.lower("10");
System.out.println(lower);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
Leo
  • 5,017
  • 6
  • 32
  • 55

2 Answers2

7

Because the values are String(s) the Set is comparing by lexical order. Please, don't use Raw Types.

NavigableSet<Integer> original = new TreeSet<>();
original.add(1);
original.add(2);
original.add(3);
original.add(4);
original.add(10);
Object lower = original.lower(10);
System.out.println(lower);

Output is

4
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
3

thats because you are comparing Strings here, and not as assumed integers. So the actual order in the Set is : 1, 10, 2, 3, 4 !

Use the generics : NavigableSet<Integer> original = new TreeSet<>(); and add the values as integers : original.add(1); and so on.

Terry Storm
  • 497
  • 3
  • 14