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