I am a bit confused on how the sort method of the Collections class uses compareTo. Say for instance there is a compareTo() method which takes Alpha objects as a parameter. Is the letter of the first element being compared to the second elements letter field? Also when the value of i is printed out to the console it's not 0,1 0r -1.
The Alpha objects just have a field named letter which is a String type.Code:public int compareTo(Alpha a){ int i = letter.compareTo(a.letter); return i; }
Code:List<Alpha> alpha = new ArrayList<Alpha>(); alpha.add(new Alpha("z")); alpha.add(new Alpha("g")); alpha.add(new Alpha("k")); alpha.add(new Alpha("q")); alpha.add(new Alpha("a")); alpha.add(new Alpha("b")); alpha.add(new Alpha("o")); alpha.add(new Alpha("v")); alpha.add(new Alpha("c")); Collections.sort(alpha); System.out.println(alpha);





Reply With Quote