Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

collection problem?? please solve

 
himanshu kesarwani
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!!
 
Treimin Clark
Ranch Hand
Posts: 757
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
QuoteYourSources
UseCodeTags
 
Harshit Rastogi
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please used code tags ..
 
Harshit Rastogi
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic