This is some information on the Java 6 certification that I prepare. This information is not very well structured and it is most of the time an answer to the questions that come when I read the SCJP 6 book (Bates and Sierra). *** AS OF 5 OF MARCH 2010, I AM SCJP 6.0 ***

Friday, January 15, 2010

16 - Comparable and Comparator - level basic - Java 1.6.0_17 - NB 6.8

public class DVD implements Comparable {

    String title;
    String genre;
    String leadActor;

    DVD(String t, String g, String a) {
        title = t;
        genre = g;
        leadActor = a;
    }

    String getGenre() {
        return genre;
    }

    @Override
    public String toString() {
        return title + " " + genre + " " + leadActor;
    }

    public int compareTo(DVD o) {
        //throw new UnsupportedOperationException("Not supported yet.");
        return title.compareTo(o.title);
    }
}

import java.util.Comparator;

public class GenreSort implements Comparator {

    public int compare(DVD o1, DVD o2) {
        //throw new UnsupportedOperationException("Not supported yet.");
        return o1.getGenre().compareTo(o2.getGenre());
    }

}

import java.util.ArrayList;
import java.util.Collections;

public class TestDVD {

    ArrayList dvdList = new ArrayList();

    void populateList() {
        dvdList.add(new DVD("title5", "genre4", "actor2"));
        dvdList.add(new DVD("title4", "genre3", "actor1"));
        dvdList.add(new DVD("title3", "genre2", "actor4"));
        dvdList.add(new DVD("title2", "genre1", "actor6"));
        dvdList.add(new DVD("title1", "genre2", "actor6"));
    }

    void go() {
        populateList();
        System.out.println("dvdlist :" + dvdList);
        Collections.sort(dvdList);
        System.out.println("dvdlist :" + dvdList);
        GenreSort gs  = new GenreSort();
        Collections.sort(dvdList, gs);
        System.out.println("dvdlist :" + dvdList);
    }

    public static void main(String[] args) {
        new TestDVD().go();
    }
}

run:
dvdlist :[title5 genre4 actor2, title4 genre3 actor1, title3 genre2 actor4, title2 genre1 actor6, title1 genre2 actor6]
dvdlist :[title1 genre2 actor6, title2 genre1 actor6, title3 genre2 actor4, title4 genre3 actor1, title5 genre4 actor2]
dvdlist :[title2 genre1 actor6, title1 genre2 actor6, title3 genre2 actor4, title4 genre3 actor1, title5 genre4 actor2]


A) The class implements Comparable (is thus modified) and the list is sorted on titles.
B) A new Comparator is implemented and the class is sorted on genres using the class GenreSort.
C) You can avoid to return something from a method if you throw an Exception. Did you know that ?

No comments:

Post a Comment

Followers