3 Replies Latest reply on Apr 23, 2008 2:27 PM by 843789

    Comparing Comparable to Comparator

    843789
      Hi,

      I am reading about Collections class and I got stuck where two interfaces (Compareable and Comparator) are being explained.

      It says that for the Comparable interface you must modify the class whose instances you want to sort+. I could follow the meaning of instances of class and sorting them, say putting those in a ArrayList but I do not understand when it says that you must modify the class_ whose instances you want to sort.

      Also for the Comparator interface : You build a class separate from the class whose instances you want to sort.


      I am also putting the code example and will very much appreciate if some one can use the references from the following code to explain the above two points.
      Thanks,
      import java.util.*;
      import java.io.*; // populateList() needs this
      public class TestDVD {
      ArrayList<DVDInfo> dvdlist = new ArrayList<DVDInfo>();
      public static void main(String[] args) {
      new TestDVD().go();
      }
      public void go() {
      populateList();
      System.out.println(dvdlist); // output as read from file
      Collections.sort(dvdlist);
      System.out.println(dvdlist); // output sorted by title
      GenreSort gs = new GenreSort();
      Collections.sort(dvdlist, gs);
      System.out.println(dvdlist); // output sorted by genre
      }
      
      public void populateList() {
      // read the file, create DVDInfo instances, and
      // populate the ArrayList dvdlist with these instances
      }
      }