It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes collection problem?? please solve Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "collection problem?? please solve" Watch "collection problem?? please solve" New topic

collection problem?? please solve

himanshu kesarwani
Ranch Hand

Joined: Aug 27, 2008
Posts: 84
import java.util.*;
class GenreSort implements Comparator<DVDInfo> {
public int compare(DVDInfo one, DVDInfo two) {
return one.getGenre().compareTo(two.getGenre());
The method returns an int whose meaning is the same
as the Comparable.compareTo() method's return value. In this case we're taking
advantage of that by asking compareTo() to do the actual comparison work for
us. Here's a test program that lets us test both our Comparable code and our new
Comparator code:
import java.util.*;
import*; // populateList() needs this
public class TestDVD {
ArrayList<DVDInfo> dvdlist = new ArrayList<DVDInfo>();
public static void main(String[] args) {
new TestDVD().go();
public void go() {
System.out.println(dvdlist); // output as read from file
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

please tell me how comaparator is working here!!

Treimin Clark
Ranch Hand

Joined: Nov 12, 2008
Posts: 757
Harshit Rastogi
Ranch Hand

Joined: Apr 15, 2008
Posts: 131
please used code tags ..

My Techie Blog - Java Questions
Harshit Rastogi
Ranch Hand

Joined: Apr 15, 2008
Posts: 131
for the below line to execute

The DVDInfo class must implement Comparator or Comparable interface.

for the line

The Comparator to sort will be GenreSort. And there you can see than comparison is made with the genre field, hence the sort is done by genre.
Where in first case you DVdInfo class must be implementing either one of the interface mentioned above and will be using title to sort it in the overriding mehtod.
I agree. Here's the link:
subject: collection problem?? please solve
It's not a secret anymore!