Wednesday, 26 February 2014

Comparing two objects of a class using compareTo()


To compare to objects we use object1.compareTo(object2)
Let's see how it works with the statement below.

int x=b.compareTo(a); //Comparing a and b


The value x will show the result of comparison.

Value of x                                              Assertion from value of x
x>0                                                                       b>a
x<0                                                                       b<a
x=0                                                                       b==a


You can make your own conditions for comparing two objects by overriding .compareTo()
i.e implementing java.util.Comparable .


For comparing two objects of same class you must use interface Comparable available in java.util.*;


So let's consider a basic example.


import java.util.*;
public class sam{
public static void main(String[] args)
{
Test a=new Test(); //Object a
Test b=new Test(); //Object b
a.c=-50; //Assigning variable c of object a to -50
b.c=55; //Assigning variable c of object b to 55



int x=b.compareTo(a); //Comparing a and b
System.out.println(""+x);
}
}
class Test implements Comparable{
Integer c;
public int compareTo(Object t)
{
Integer v=10;
return c.compareTo(v); //this is a test condition
}
}


Output will be
1



Explanation of code:
We have created a public class sam in it's main method we created two instances of Test class which are a and b. Now we assign the variable c of object a to -50 and variable c of object b to 55.
Now int x=b.compareTo(a); will show the comparision value.
In class Test we implement Comparable and override compareTo(), and return the result .The Integer v is a dummy to compare the object .You can use instead of v your instance variables such as price,id no etc.


No comments:

Post a Comment