Comparable and Comparator Interface - Collections

Hi All
Please let me know when to use Comparable interface and Comparator interface. ?
Any sort of information is highly appreciable .
Matt

Matt wrote:
@ jverd      
So, when you googled, and found tutorials, and worked through those tutorials, and read the javadocs for those classes, what in particular did you not understand?If everything would work like that what will be the use of forums like this , It does work like that, for people who aren't lazy. The use of these forums, as indicated by my first reply, is among other things, when you've done your own research, as you should do, and run into something you don't understand.
so dont try to be smart :(Maybe you should try to be smarter.
Lets try not to abuse the forum with exchanges like this. The only abuse so far has been you expecting the forum to be a substitute for doing your own research.
I know how to use Comparable and Comparator but dont know when to use these in a real time application.That statement says nothing about your problem. The only information it carries is that you don't know what the term "real time" means.

Similar Messages

  • Comparable and comparator interface in java

    Hi All,
    How comparable and comparator interface works in java and when to use comparable and when to use comparator.please give me some example(code) as I am not able to understand the difference.
    Thanks
    Sumit
    Edited by: sumit7nov on May 17, 2009 4:45 AM

    Thanks,one more doubt.
    We have Collections.sort() method and we can sort any list by this method without implementing comparable or comparator interface.Then my question is when we need to implement comparable or comparator interface or when do we write our own compareTo() or compare() methods.
    Thanks
    Sumit

  • Comparable and Serializable interfaces

    Hi All,
    I have developed a program in java which implements Comparable and Serializable Interfaces. After, I decided to run the program in J2ME. But later on, I found that MIDP doesn't implement these interfaces.
    Some one can help me how to implement my own interfaces.
    Thank you

    Hi Supareno
    I need urgently your help.
    I developed Java program which works as predicitive text system for my mother tongue.I would like to move from Java to J2ME. But until now I have problems. please can u help me. the following code run in command line.
    I tried to develop my own interfaces as you told me but it doesn't work.
    Help me also for reading and writing text files.
    Thank you
    import java.util.*;
    import java.io.*;
    import java.util.Vector;
    import java.util.Enumeration;
    public class PredText {
    private Vector dict;
    public static final String dictionaryFile = "C:/java/words.txt";
    // convert a string to the corresponding signature
    public static String toNumeric (String word) {
    String lowerWord = word.toLowerCase();
    StringBuffer result = new StringBuffer("");
    for (int i = 0; i < lowerWord.length(); i++) {
    char c = lowerWord.charAt(i);
    if ("abc".indexOf(c) > -1) result.append("2");
    else if ("def".indexOf(c) > -1) result.append("3");
    else if ("ghi".indexOf(c) > -1) result.append("4");
    else if ("jkl".indexOf(c) > -1) result.append("5");
    else if ("mno".indexOf(c) > -1) result.append("6");
    else if ("pqrs".indexOf(c) > -1) result.append("7");
    else if ("tuv".indexOf(c) > -1) result.append("8");
    else if ("wxyz".indexOf(c) > -1) result.append("9");
    else if (" ".indexOf(c) > -1) result.append("9");
    else result.append("?");
    return result.toString();
    // find all the words corresponding to a signature
    public Vector findMatches(String sig) {
    WordSig ws = new WordSig(sig, "");
    WordSig newws;
    Vector results = new Vector();
    int index;
    index = Collections.binarySearch(dict, ws);
    if (index < 0){
    // no matches! :(
    // try to get the string that starts with a substring like ours.
    index=-1-index;
    if (((WordSig)dict.get(index)).getSig().startsWith(sig)) {
    // no word found. we return those starting with the
    // same signature
    newws = (WordSig) dict.get(index);
    results.addElement(newws.getWord().substring(0,sig.length()));
    return results;
    } else{
    //no match
    return results;
    } else {
    // go back to the first match
    while(((WordSig)dict.get(index)).getSig().equals(sig) && index>0)
    index--;
    if (index != 0)
    index++;
    while ((newws = (WordSig) dict.get(index)).equals(ws)){
    results.addElement( newws.getWord() );
    index++;
    return results;
    // intialises the dictionary
    public PredText () {
         String word;
    String sig;
    Vector dict = null;
    // first try to load dict.dat
    try {
    System.out.print("Trying to load dict.dat...");
    FileInputStream fileStream = new FileInputStream("C:/java/dict.dat");
    ObjectInputStream objectStream = new ObjectInputStream(fileStream);
    dict = (Vector) objectStream.readObject();
    fileStream.close();
    System.out.println(" done.");
    }catch (ClassNotFoundException classNotFoundException) {
         System.out.println("Unable to create an object");     
    catch (IOException e) {
    // exception: create the dictionary
    System.out.println("Error. I'm going to recreate the dictionary file");
    try {
    dict = createDict();
    catch (IOException ioe) {
    System.err.println("Error while creating dictionary file. Exiting." + e);
    System.exit(1);
    this.dict = dict;
    // create the dictionary serialised file
    public Vector createDict () throws IOException {
    String word;
    Vector dict = new Vector();
    //open the dictionary file
    System.out.print("Reading the dictionary... ");
    BufferedReader dictFile = new BufferedReader(
    new FileReader(dictionaryFile));
    //insert each word into the data structure
    while ((word = dictFile.readLine()) != null) {
    word = word.toLowerCase();
    dict.addElement(new WordSig(toNumeric(word), word));
    // List list = dict.subList(0, dict.size());
    List list = dict.subList(0, dict.size());
    Collections.sort(list);
    System.out.println("done.");
    System.out.print("Writing the dictionary... ");
    FileOutputStream fileStream = new FileOutputStream("C:/java/dict.dat");
    ObjectOutputStream objectStream = new ObjectOutputStream(fileStream);
    objectStream.writeObject(dict);
    objectStream.flush();
    fileStream.close();
    System.out.println("done.");
    return dict;
    public static void main (String args[]) {
         PredText pt = new PredText();
    if (args.length == 0) {
    // no arguments, find the largest clash
         Vector result;
         Enumeration e = pt.dict.elements();
    String currentSig = "";
    String prevSig = "";
    int clash = 0;
    int maxClash = 0;
    String clashSig = "";
    while (e.hasMoreElements()) {
    WordSig ws = (WordSig) e.nextElement();
    currentSig = ws.getSig();
    if (currentSig.equals(prevSig)) {
    // another word with the same signature
    clash ++;
    } else {
    // new signature: check if the previous one led
    // to a maximal clash
    if (clash > maxClash) {
    clashSig = prevSig;
    maxClash = clash;
    clash = 1;
    prevSig = currentSig;
    result = pt.findMatches(clashSig);
    System.out.println("The signature leading to most clashes is "
    + clashSig + " with " + result.size() +
    " number of clashes");
    for (int j = 0; j < result.size(); j++) {
    System.out.println((String)result.get(j));
    } else if ("0123456789".indexOf(args[0].charAt(0)) > -1){
    // numeric input: find the matches for the argument
    Vector result;
    result = pt.findMatches(args[0]);
    for (int j = 0; j < result.size(); j++) {
    System.out.println((String)result.get(j));
    } else {
    // convert each word to the corresponding signature
    for (int i = 0; i < args.length; i++) {
    System.out.print(toNumeric(args) + " ");
    class WordSig implements Comparable, Serializable {
    String word;
    String sig;
    public WordSig (String sig, String word) {
    this.sig = sig;
    this.word = word;
    public String getSig () {
    return this.sig;
    public String getWord() {
    return this.word;
    public int compareTo (Object ws) {
    return sig.compareTo(((WordSig) ws).getSig());
    public boolean equals (Object ws) {
    return sig.equals(((WordSig) ws).getSig());
    public String toString () {
    return sig + ", " + word;

  • Comparable and Serializable Interfaces in MIDP

    Hi All,
    I have developed a program in java which implements Comparable and Serializable Interfaces. After, I decided to run the program in J2ME. But later on, I found that MIDP doesn't implement these interfaces.
    Some one can help me how to implement my own interfaces.
    Thank you

    Thank you for replying to me.
    My problem is to compare to objects in MIDP.
    You know that in java is possible to implements directly the Comparable interface but in MIDP is not the same. So I think it requires to create your own. Is that my question.
    I need some to help me. just to avoid the implentation of comparable interface from the java lang package.
    Thank u.

  • Sort column by without case sensitive  using Comparator interface

    Hello,
    When i sorted my values of a column in a table it was showing all sorted upper case letters at top rows and all sorted lower case letters on bottom. So i would like to sort values without case sensitive order. Like. A, a, B, b, C, c....
    I am using Collection class to sort vector that contains the values of a column as an object and using Comparator interface to sort the values of a column in either ascending and descending order. It facilitates to compare two objects like.
    <class> Collections.sort(<Vector contains values of column to be sort>, <Comparator interface>);
    and in interface it compares two objects ((Comparable) object).compareTo(object);
    Now Let's suppose i have three values say Z, A, a to sort then this interface sorted in ascending order like A, Z, a
    but the accepted was A, a, Z. So how can i get this sequence. I would like to sort the values of a column without case sensitive manner.
    Thanks
    Ashish Pancholi
    Edited by: A.Pancholi on Dec 29, 2008 1:36 PM

    [http://java.sun.com/javase/6/docs/api/java/lang/String.html#CASE_INSENSITIVE_ORDER]

  • How can I compare two collections at the same time? (View two grid views)

    I have two collections containing some of the same images. (My Nikon D70 did not put an end-of-file on some images. I recovered them into a different collection.) Now I want to display both collections side-by-side in grid view. I will select those images in the "recovered" collection that correspond to the bad images in the "main" collection, add the ratings etc, and move just these to another collection.
    It is extremely frustrating to have to bounce back and forth between collections, remembering each image one by one and selecting it in the "recovered" collection. (The image names are not preserved in the "recovered" collection -- I have to go by what the image looks like.)
    LightRoom allows me to compare photos in the compare view. I want to compare collections in two grid views.

    CaptureTheLight,
    you have ran into a situation when you have to compare two sets of images and now you're wondering how come Lightroom doesn't have such "obviously necessary" functionality? But you have to admit it, this is not such a common situation in a photographer's workflow recovers broken files and tries to compare them against themselves. I think it's a pretty specific feature you need. Still, Lightroom has enough powerful tools for editing and sorting images.
    For example...
    You could just put them all - "main" and "recovered" - into a single collection or into the Quick Collection. Label the entire "recovered" collection with, say, red and sort by capture time. Now you'll have everything side by side, ordered chronologically. The "recovered" images will stay next to the "main" images since their capture time will be the same, and they will also stand out since they have the red label.
    Make the thumbnails bigger and set up the grid view so it tints the thumbnail cell are tinted with the label color. Now, you can go quickly through them visually checking labeled vs unlabeled.

  • Using the Comparator Interface.Please Help.

    Hello there,
    I am trying out this example regarding the Comparator Interface.
    It works fine, but I havent really understood this at all.
    It deals with reverse sorting.
    import java.util.*;
    class MyComp implements Comparator {
    public int compareTo(Object a,Object b)
    String aStr,bStr;
    aStr = (String)a;
    bStr = (String)b;
    return bStr.compareTo(aStr)
    class MyComparator {
    public static void main(String[] args) {
    // Create a Tree Set
    TreeSet ts = new TreeSet(new MyComp());
    ts.add("C");
    ts.add("A");
    ts.add("P");
    ts.add("Z");
    ts.add("B");
    System.out.println(ts)
    Output : [Z, P, C, B, A]
    I have not understood the following at all:
    1) We are implementing the Comparator Interface in class MyComp.
    Now where is this being called in the MyComparator class?
    2) How is the reverse sorting taking place.?
    How is this comparing the different instances of the MyComparator class
    when I havent even instantiated the MyComparator class ?
    3) How is the interface method compare To(Object a,Object b) being invoked?
    Please can some please answer my questions.
    Regards

    class MyComp implements Comparator {
    public int compareTo(Object a,Object b)
    String aStr,bStr;
    aStr = (String)a;
    bStr = (String)b;Your reverse ordering is happening here.
    If you were to write
    return aStr.compareTo(bStr)
    the ordering would be in normal order.
    >
    return bStr.compareTo(aStr)The comparator that the treeSet uses is declared and instantiated here
    TreeSet ts = new TreeSet(new MyComp());
    1) We are implementing the Comparator Interface in
    class MyComp.
    Now where is this being called in the MyComparator
    or class? The comparator is being used by the TreeSet to order your entries
    >
    >
    2) How is the reverse sorting taking place.?Explained above. For further explaination look up comparator and String.compareTo()
    How is this comparing the different instances of
    of the MyComparator class
    when I havent even instantiated the MyComparator
    or class ?Also explained above
    3) How is the interface method compare To(Object
    a,Object b) being invoked?Internally by the TreeSet
    I hope this helped a little

  • How to use the Comparable Interface?

    Now I have a question and I don't quite understand what the book explains. How does the comparable interface work? How can you redefine the equals implementation? How can you implement a compareTo? and how does this works with arrays? Thanks amigos......

    Not sure how to answer your question "how does the Comparable interface work" - what do you mean by "work"? It's purpose is to supply a known method that can be used to define an ordering on lists of objects. To do this you need to know how two objects compare to each other (less than, equal to, greater than) - and that's what the compareTo method gives you.
    You redefine the equals implementation by overriding the equals method - just declare a method in your class that has the same signature as equals and you're good.
    Your implementation of compareTo depends on your class. You just need to define how your classes compare to each other - for instance, assume you have an "Employee" class, that has an employee number and first name and last name fields. You want the natural ordering of lists of Employees to go in order by employee number. Define your compareTo method like:
    public int compareTo(Object o) {
        Employee emp = (Employee)o;
        if (emp.getEmployeeNumber() < this.getEmployeeNumber()) {
            return -1;
        else if (emp.getEmployeeNumber() == this.getEmployeeNumber()) {
            return 0;
        else {
            return 1;
    }You can sort arrays of things via the Arrays.sort method, which takes the array to sort and a Comparator (not Comparable) reference. The Comparator interface provides the same idea as the Comparable interface, but it's a stand-alone object that handles the comparison, as opposed to a method of some particular class. The compareTo method of the Comparator interface takes two Object references and returns how they compare.
    Good luck
    Lee

  • Comparable interface selection sort

    Hi,
    I've created a Person Class with a comparable interface. And i've created an ArrayList People with varaibles from the person class in - First_name, Surname, Month(Birthday), Day(Birthday).
    Now i need to use selection sort to sort my arraylist into birthday order. In the Person Class i have a method which gives each person a different number for every possible birthday there is.
    I have created a selction sort but dont know how to call the birthday from my array list and then to sort it.
    This is my code for the selection sort so far:
    import java.util.ArrayList.*;
    public class Main
    public static void selectionSort(Comparable[] people)
    for (int k = people.length-1; k>0; k --)
    Comparable tmp;
    int Large = 0;
    for (int j=1; j<= k; j++)
    if (people[j].compareTo(people[k]) <0)
    Large = j;
    tmp = people[Large];
    people[Large] = people[k];
    people[k] = tmp;
    this method compiles but i need to sort the birthday and dont know how. Also i need to output the whole array in birthday order.
    Any help would be very greatful.
    Thanks
    Dave

    Hi,
    If my understanding is right..
    You are trying to sort with birthday as the primary sort criterria.
    For doing that, you have to write the comparison logic inside the compareTo() method implemented in the Person class (Inherited from Comparable Interface).
    i.e. The compareTo() method should use the the primary_sort_variable(here it is birthday or something derived from it) to return a boolean value for your need.

  • Trying to implement comparable interface

    I am writing a Book class, and in the class header I have stated the implements Comparable. I also have defined the public int compareTo( Book rhs). When I compile the Book class. I get the following message. The Book class needs to be abstract.
    I cannot create an object from an abstract class. What am I doing wrong?
    Ray

    You have maybe not implemented all methods in the interfaces you are using in your Book class. Are you using any other interface than Compnarable? Do you get any other error message?
    Anyway, this works when adding the Comparable interface, add this method to your Book class:
    public int compareTo(Object o) {
    return this.toString().compareTo(o.toString());
    And this method:
    public String toString() {
    return bookName; // Or anything that represents your book (for comparing)

  • Why don't we  want to define equals() in Comparator interface...........

    Comparator interface has two methods: compare() & equals(). If we implement Comparator in our class(not abstract) itz unnecessary to define equals(). Why? (If we implement an interface we should define all its methods inside the class where we implement it)....

    It all hinges on what the type of Object is. Is it
    of type Comparator or the parameter you expect to be
    passed to compareTo?
    I say that Comparator makes the most sense to me.
    If you read Joshua Bloch's stuff about Comparable, he
    says it's very important to make sure that compareTo
    obeys the same contract as equals for that object.
    Why would you want to try overriding the behavior
    that might already exist in the Object that's the
    parameter for compareTo? That would be bad design,
    IMO. You might change the intentions of the person
    who wrote that class.
    %the docs say it's for comparing Comparators.
    from the docs:
    Additionally, this method can return true only if the specified Object is also a comparator and it imposes the same ordering as this comparator
    I read that to mean that the compared objects should both be Comparators (obviously) and both result in the same ordering. seems to me the method is declared on this interface to draw attention to this addition to the contract, as much as anything else

  • Comparable Interface

    I'm having trouble with my comparable interface...basically I just need to order a list by last name.... I'm getting a java.lang. class cast exception. I'm not sure why. I'll give some code but I have an Employee object with all the normal stuff name, salary etc. I throw those in a node and threw the node in an Object List. So here's my Object list method.../**
         * Inserts a node into its correct location within an ordered list
         * @param o - The element to be inserted into the list
        public void insert(Object o) {
            ListNode p = list;
            ListNode q = null;
            while (p != null && ((Comparable)o).compareTo(p.getInfo()) > 0) {
                q = p;
                p = p.getNext();
            if (q == null)
                addFirst(o);
            else
                insertAfter(q, o);
        }Here's my Employee class method: public int compareTo(Object o)
            Employee e = (Employee) o;
            return lastName.compareTo(e.getLastName());
        }My comparable class is normal...what you expect it to be and here's my call....
    public void orderList()
            ObjectList newList = new ObjectList();
            Iterator list = new Iterator(employeeObjectList);
            Employee e;
            while(list.hasNext())
                e = (Employee)list.query();
                newList.insert(e);
                list.next();
                   I might be doing this all wrong. I know eventually I will code it right but I'd like to have a better understanding of how the comparable interface works. If someone could give some thoughts I would appreciate it.

    while (p != null && ((Comparable)o).compareTo(p.getInfo()) > 0) {It looks like either the object you're trying to insert doesn't implement Comparable, or whatever is returned by p.getInfo() doesn't implement Comparable. If you know they're both Employees, then make sure the Employee class is actually declared to implement Comparable, and if you're using JDK 1.5 or later you might consider using generics to avoid some of the casts.
    public class Employee implements Comparable<Employee> {
        public int compareTo(Employee e) {
            return lastName.compareTo(e.getLastName());
    }

  • Stuck using the Comparable Interface

    I am having problems implementing the Comparable Interface in my class. I have written the compareTo method but this is not working. Can anyone see what I am doing wrong in the coding of this method. Thanks !!. (see below code for the class :
    package tma02q1;
    import java.util.*;
    This is the outline of the basic Video class.
    Such a class describes the videos stocked by a branch of a video hire company
    As well as completing the given methods you will need to make further additions
    to this class.For further details you should study the BranchTest class.
    public class Video implements Comparable {
    // declare two instance variables
    // a String to hold the video title
    // an int to hold the video rental cost - cost is held in pence
    private String aTitle;
    private int aCost;
    public Video(String aTitle, int aCost) {
    this.aTitle = aTitle;
    this.aCost = aCost;
    private void setTitle(String aTitle) {
    this.aTitle = aTitle;
    public String getTitle() {
    return aTitle;
    private void setRentalCost(int aCost) {
    this.aCost = aCost;
    public int getRentalCost() {
    return aCost;
    public String toString() {
    return "Video Title = " + aTitle + " which has a rental cost of = " + aCost;
    public boolean equals(Object vid) {
    Video arg = (Video) vid;
    return (this.aTitle.equals(arg.aTitle)
    &&this.aCost==arg.aCost);
    public int compareTo(Object vido) {
    Video arg = (Video) vido;
    int comp = aCost.compareTo(arg.aCost);
    return comp;

    You've got another serious problem with your code. Both the equals and compareTo methods will throw a ClassCastException if the parameter is not a reference to a video object. Using the instanceof operator will however solve the problem. E.g.
    public boolean equals(Object o) {
      if (o instanceof Video) {
        Video  arg = (Video) o;
        return (this.aTitle.equals(arg.aTitle)
                &&this.aCost == arg.aCost);
      else
        return false;  
    }The same approach is applicable to the compareTo method.
    Regards

  • Compare two collection in sharepoint

    Hii
    I want to Compare to collection in sharepoint
    example:
    Collection 1: "A","B","C"
    Collection 2:"A","B","D","E"
    Result should be: "C"
    Like in C#  List<string> result = list1.Except(list2).ToList();
    I am new to programming Please help me..
    regards 
    sudeep

    http://stackoverflow.com/questions/3407356/comparing-two-collections
    check this example code below
    class CompareLists
    static void Main()
    // Create the IEnumerable data sources.
    string[] names1 = System.IO.File.ReadAllLines(@"../../../names1.txt");
    string[] names2 = System.IO.File.ReadAllLines(@"../../../names2.txt");
    // Create the query. Note that method syntax must be used here.
    IEnumerable<string> differenceQuery =
    names1.Except(names2);
    // Execute the query.
    Console.WriteLine("The following lines are in names1.txt but not names2.txt");
    foreach (string s in differenceQuery)
    Console.WriteLine(s);
    // Keep the console window open in debug mode.
    Console.WriteLine("Press any key to exit");
    Console.ReadKey();
    /* Output:
    The following lines are in names1.txt but not names2.txt
    Potra, Cristina
    Noriega, Fabricio
    Aw, Kam Foo
    Toyoshima, Tim
    Guy, Wey Yuan
    Garcia, Debra
    http://msdn.microsoft.com/en-us/library/bb397894.aspx
    Mark ANSWER if this reply resolves your query, If helpful then VOTE HELPFUL
    INSQLSERVER.COM
    Mohammad Nizamuddin

  • Remote and local interface on same ejb 3.0 bean instance

    Hi,
    Is it posible to get remote and local interface on same ejb 3.0 bean instance.
    For example get local interface of a bean and than pass it as remote to client.
    Both interfaces must operate on same bean instance.
    Thanks
    Zlaja

    yes. You can implement multiple interfaces on a single class, so you can add a local and a remote interface. One trick to avoid duplicate code is to simply make the remote interface extend the local interface; then you only have to add the @Remote annotation and you're done.
    For example get local interface of a bean and than pass it as remote to client.You don't pass an instances to a client, a client looks up a remote instance of the bean through JNDI.

Maybe you are looking for

  • How to get multiple records in one row and different column

    Hi All, I am using oracle database 11g and i have a two tables table_1, table_2 table_1 having columns emp_no first_name middle_name last_name email and table_2 having columns emp_no phone_type phone_number and having entires emp_no phone_type phone_

  • Mac Book Charger - Cord strain relief begs for a fix

    After several years of good use, the original AC adapter/charger for my Mac Book developed a tear in the cord that runs from the white 'block' to the Mac. The tear in the outer cover of the cord formed adjacent to the hard plastic 'strain relief' tha

  • Access denied when jsp writes to a`network  file system

    Hi Can anyone help. Im having big problems with my web application which was working fine when it was hosted on a tomcat windows NT machine. The application was recently upgraded to a Windows 2000 machine. My jsp page which has to write to a network

  • What is in the MacBook Air accessory kit? Is there a Magic Mouse?

    I would like to know what is in the accessory kit, so I don't have to buy any extra stuff.

  • Starting database in Read only mode

    hi, i am using oracle 8i, we want to copy the Production database to other machine, but on starting that m/c database should be opened in read only mode without DBA interaction what to do for that. pl tell thanx in advance