How is 1 more than 4?

NavigableSet.lower(E) Javadoc says that it returns the largest element in this set is strictly less than the given element, or null if there is no such element. Why is the conclusion here? Shouldn't 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); 
+5
source share
2 answers

Since the values ​​are String (s), Set compared in lexical order . Please do not 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); 

Exit

 4 
+7
source

thats because you are comparing strings here, and not as intended integers. Thus, the actual order in the set: 1, 10, 2, 3, 4!

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

+3
source

Source: https://habr.com/ru/post/1205438/


All Articles