aspose file tools*
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "collection problem?? please solve" Watch "collection problem?? please solve" New topic
Author

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 Comparator.compare() 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 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
}
}

please tell me how comaparator is working here!!


SCJP 5
Treimin Clark
Ranch Hand

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

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


<a href="http://technologiquepanorama.wordpress.com" target="_blank" rel="nofollow">My Techie Blog</a><br /><a href="http://www.java-questions.com" target="_blank" rel="nofollow">Java Questions</a>
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: http://aspose.com/file-tools
 
subject: collection problem?? please solve