Results 1 to 12 of 12
  1. #1
    chathura87 is offline Member
    Join Date
    Feb 2011
    Posts
    27
    Rep Power
    0

    Default I don't understand comparable Interface Please help me

    I don't understand how the comparing happens with comparable interface..
    I know i've to implements comparable interface to sort 2 objects given criteria.

    Please check following code. It does not give proper output why is that???

    Thank you very much

    import java.util.*;

    class Testx{

    public static void main(String[] args){

    Emp e1=new Emp("a");
    Emp e2=new Emp("abb");
    Emp e3=new Emp("xyz");


    ArrayList<Emp> stuff=new ArrayList<Emp>();

    stuff.add(e1);
    stuff.add(e2);
    stuff.add(e3);

    System.out.println(stuff);
    Collections.sort(stuff);
    System.out.println(stuff);

    }


    }

    class Emp implements Comparable<Emp>{

    String name;
    Emp(String name){

    this.name=name;

    }

    public String getName(){

    return this.name;

    }


    public int compareTo(Emp e){

    return name.compareTo(e.getName());

    }

    }
    Last edited by chathura87; 03-01-2011 at 04:59 AM.

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    I copy and pasted it. You didn't override toString()

    so you get some funny looking stuff
    Java Code:
    [Emp@6af62373, Emp@459189e1, Emp@55f33675]
    [Emp@55f33675, Emp@6af62373, Emp@459189e1]
    This funny looking stuff is a hex representation of the hashcode.

    Try overriding toString() and then it will work correctly. You can however tell from the hashcodes that the list is reorganized.

    By the way, the comparable interface lets you choose how you want to determine if one object is larger than another. This lets you decide that a should come before/after z. It then uses this definition of which comes first and applies a sort to the objects using that as a comparison.

    If you did the sort by yourself on just numbers you would take two numbers and determine which is larger or smaller and move through the list placing the correct item in the correct space. This simply gives the Collections.sort method something to use to determine whats < and >.

    I can't remember what sort is used exactly, but, off the top of my head, I believe mergesort is used for object sorting.
    Last edited by sunde887; 03-01-2011 at 05:02 AM.

  3. #3
    chathura87 is offline Member
    Join Date
    Feb 2011
    Posts
    27
    Rep Power
    0

    Default

    Thank you for your quick reqply first of all..

    Emp e1=new Emp("a");
    Emp e2=new Emp("abb");
    Emp e3=new Emp("xyz");


    output is:
    Emp@42e816, Emp@19821f, Emp@addbf1

  4. #4
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,788
    Rep Power
    7

    Default

    You attempting to print the ArrayList and not its contents. If you want the contents to be displayed then iterate over the List and print each object.

  5. #5
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    The only real error here is that he isn't defining a toString. When you do something like
    Java Code:
    ArrayList<String> anAL = new ArrayList<String>();
    //fill anAL
    System.out.println(anAl);
    will produces
    Java Code:
    [string1, string2, string3]
    The problem is that all the arraylists toString method does is print each item in the array list
    Java Code:
    class ArrayList{
      toString(){
        StringBuilder sb = new StringBuilder("[");
        for(int i = 0; i < arrayList.length; i++){
          sb.append(arrayList.get(i));
          sb.append(", ");
        }
        sb.delete(arrayList.length);
        sb.append("]");
      }
    }
    this is basically what the arraylists tostring method does.

    In actuality, it calls the toString() of each object in the arrayList.

    default toString will look like this
    Java Code:
    ClassName@a1f3h3f
    Which is the classname and the hex representation of a hashcode.

    Try overriding toString in your Emp class than see what happens.

  6. #6
    chathura87 is offline Member
    Join Date
    Feb 2011
    Posts
    27
    Rep Power
    0

    Default

    Hi i've implmented comparaTo method like this:

    Now here in the emp objects i've sorted according to the name.

    In compareTo method looks like: (i used SCJP Kathy's book to write this)

    public int compareTo(Emp e){

    return name.compareTo(e.getName());

    }


    I don't understand how comparing happens Can you please explain it??

    I don't understand how cmparaing happens?

    In method i takes Emp e ... But which (Emp e) it takes??? i mean with which object it does comparation this object.. Hope i explained my problem correctly...Thank you very much
    i'm confused...

    public int compareTo(Emp e){

    return name.compareTo(e.getName());

    }

  7. #7
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,788
    Rep Power
    7

    Default

    You call the Collections.sort method. This method will call the objects compareTo method. Pseudocode:
    Java Code:
    loop over List {
        if obj1.compareTo(obj2) is greater than 0 {
            swap obj1 and obj2;
        }
    }
    Or whatever sorting algorithm the sort method implements.

  8. #8
    chathura87 is offline Member
    Join Date
    Feb 2011
    Posts
    27
    Rep Power
    0

    Default

    oh.. IT MEANS one by one it travels through all objects right!!??
    But why we should use <Emp> in the class declaration??? What is the point, we could have just use Emp only in compareTo method right??

    Thanks a lot for i cleared many from the help of you guys

    class Emp implements Comparable<Emp>{ //

  9. #9
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    first thing, you need a method in your emp class to get everything working correctly.

    Java Code:
    public String toString()
    is what it should look like.

    When you use compareTo it compares it to this.

    for example, you could do
    Java Code:
    public int compareTo(Emp e){
      this.name.compareTo(e.name);
    }
    But since you are making this inside the class you don't need to supply this, it works with just
    Java Code:
    public int compareTo(Emp e){
      name.compareTo(e.name);
    }
    The next thing to cover here is how it looks if you actually used it.

    Say you create two employee objects
    Java Code:
    Emp e1 = new Emp("Bob");
    Emp e2 = new Emp("Lex");
    e1.compareTo(e2);
    /**
     * this says the following
     * public int compareTo(Emp e2){
     *   e1.name.compareTo(e2.name);
     **/
    Try creating those two objects and writing that line of code, compile, and run it and see what it produces.

    It should produces some int, im leaving that for you to try.

    With this return value the sort method does the comparison.

    Normally a compareTo method you would define the method much more throughly

    Since you are comparing two String objects you simplify it by using Strings built in compareTo method.

    If you want to see what that looks like you can look up the String class source code, but you can just accept that it works correctly.

    the <Emp> is the generics, it tells the compiler what type is to be expected in that comparable/comparator. I am a bit uneducated when it comes to generics so others will have to give you a more detailed explanation.

    The sort method uses a mergeSort type sorting algorithm and just goes through the entire list and places the items in the correct spot. If you google Collections.sort API and then search through for the sort method it tells you a bit more detail about how it works. However, a lot of this is probably more than you need to know right now and you can just accept that it works correctly.
    Last edited by sunde887; 03-01-2011 at 05:31 AM.

  10. #10
    chathura87 is offline Member
    Join Date
    Feb 2011
    Posts
    27
    Rep Power
    0

    Default

    I'm trying Very good explanation Thanks a lot..
    I think Comprator interface also same as this...

    Have a nice day friends..

  11. #11
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Comparator interface is basically identical, but can be used a bit differently, don't be afraid to come ask for help if you need explanations. Also, if you solved this, mark the thread solved with the thread tools at the top.

  12. #12
    subith86 is offline Senior Member
    Join Date
    Jan 2011
    Location
    Bangalore, India
    Posts
    102
    Rep Power
    0

    Default

    The difference between comparable and comparator is that, comparable can be used to compare objects of one class and that class has to implement Comparable interface.

    But comparator can be used to compare objects of different classes. Those classes need not implement Comparator interface. Instead you can implement it in another class and pass the objects to the compare(Object, Object) method.

    Now for sorting, you have to decide how you want it to be sorted. Maybe you want to sort the objects in increasing order of one of its integer data variable. Sometimes you want to sort it according to the alphabetical order of some string data variables. Whichever the case is, the sorting logic should be done by you in the compare(Object, Object) method in case of Comparator, or in compareTo(Object) method in case of Comparable.

    An example is posted below for Comparable. Try out yourself for comparator:
    Java Code:
    public class DvdInfo implements Comparable<DvdInfo>{
    	
    	private String name;
    	private String genre;
    	private String lead;
    	
    
    	public int compareTo(DvdInfo arg0) {
    		int cmp = this.name.compareTo(arg0.name);
    		return cmp;
    	}
    }
    In my case I'm sorting List<DvdInfo> with List<DvdInfo>.
    Notice that I'm comparing two objects of same type. And compareTo method is defined in the DvdInfo class. It cannot be put in any other place.

    Now I'm sorting the object dvdInfo which is a List<DvdInfo>. I just have to do this
    Java Code:
    Collections.sort(dvdList);

Similar Threads

  1. Replies: 6
    Last Post: 01-18-2011, 02:31 AM
  2. Got hit by the Comparable block again, help pls.
    By niu_niu in forum New To Java
    Replies: 7
    Last Post: 06-24-2010, 09:49 AM
  3. Comparable Interface
    By Yelrubk in forum New To Java
    Replies: 3
    Last Post: 04-28-2010, 02:46 PM
  4. interface Comparable<T> problem
    By Lennon-Guru in forum New To Java
    Replies: 3
    Last Post: 03-05-2008, 12:17 AM
  5. i can't understand using interface as a type
    By sireesha in forum New To Java
    Replies: 3
    Last Post: 11-20-2007, 10:07 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •