Results 1 to 13 of 13

Thread: Collections.sort(List <T> list) & compareTo(T o)?

Threaded View

  1. #1

    Thread Starter
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418

    Resolved Collections.sort(List <T> list) & compareTo(T o)?

    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.
    Code:
    public int compareTo(Alpha a){
    int i = letter.compareTo(a.letter);
     return i;
    }
    The Alpha objects just have a field named letter which is a String type.
    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);

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width