PDA

Click to See Complete Forum and Search --> : Comparing Objects


x-ice
May 11th, 2006, 10:03 AM
If i have two objects how can i compare them?

For example.

I have two objects of the same class. They have a variable called 'data' which is a string.

Object 1: data = 'hello'
Object 2: data = 'bye'

I want to compare these objects to see which object would come first (alphabetically) if the 'data' variable of both objects was sorted into alphabetical order.

The order i would be order is Obect 2 and then Object 1, but how can i do this in code?

Thanks.

ComputerJy
May 11th, 2006, 03:27 PM
You can implement the interface "Comparable" in your class and return the String.compareTo(String) value

x-ice
May 12th, 2006, 04:51 AM
You can implement the interface "Comparable" in your class and return the String.compareTo(String) valueCan you give an example on how to do this? I am pretty rusty at Java these days.

ComputerJy
May 12th, 2006, 06:46 AM
public class Sample implements Comparable
{
private String str ;

public String getString () {
return str ;
}

public int compareTo (Object o) {
if (o instanceof Sample) {
return str.compareTo(((Sample) o).getString()) ;
}
else {
return str.compareTo(o.toString()) ;
}
}
}

x-ice
May 12th, 2006, 06:49 AM
public class Sample implements Comparable
{
private String str ;

public String getString () {
return str ;
}

public int compareTo (Object o) {
if (o instanceof Sample) {
return str.compareTo(((Sample) o).getString()) ;
}
else {
return str.compareTo(o.toString()) ;
}
}
}Thanks