Assuming that you are using java 1.5 or later then:
public class SomeObject implements Comparable<SomeObject> {
public boolean equals(Object obj) {
if (obj==null) return false;
if (obj instanceof SomeObject) {
SomeObject so = (SomeObject)obj;
// write your code here that compares the values of the so attributes with the attributes of this class.
}
return false;
}
public int compareTo(SomeObject o) {
// look at the API of the Comparable interface. It explains how this method should be implemented.
}
}
javaAddict
Nearly a Senior Poster
3,338 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 450
Skill Endorsements: 7
The basics of Comparable really come down to returning a negative value if "this" is less than the object passed, a positive value if "this" is greater, or zero if they're equal
class SomeClass implements Comparable<SomeClass> {
public int compareTo(SomeClass other) {
// If this < other, return -1
// If this > other, return 1
// If they're equal, return zero.
return 0;
}
}
Now all you need to do is code in the "if" statements to compare them.
Ezzaral
null
16,126 posts since May 2007
Reputation Points: 3,294
Solved Threads: 875
Skill Endorsements: 28
Thanks for the help, but if you don't mind how exactly can i do a greater or less with Strings? i would presume alphabetically but is that really veasible?
inside compareTO you should use compareTo again which will return 1/0/-1, you shouldnt do < but compareTo ... for example.
public int compareTo(Object obj){
Employee emp = (Employee) obj;
if(this.firstName.compareTo(emp.firstName)!=0)
return this.firstName.compareTo(emp.firstName);
}else if(this.middleName.compareTo(emp.middleName)!=0){
return this.middleName.compareTo(emp.middleName);
}else if(this.lastName.compareTo(emp.lastName)!=0){
return this.lastName.compareTo(emp.lastName);
}else
return 0;
if firstname !=0 then it will return 1/-1 and if they are equal it will chk for middle name, if middle name is not equal it will return 1/-1
else it will chk for last name
vchandra
Junior Poster in Training
73 posts since Mar 2010
Reputation Points: 13
Solved Threads: 14
Skill Endorsements: 0
Since vchandra has already answered your question, I would like to add that any class that implements the Comparable interface can be sorted using the compareTo method. If you look at the API the String class implements the Comparable, so it has a "compareTo" method that you can call.
javaAddict
Nearly a Senior Poster
3,338 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 450
Skill Endorsements: 7
Question Answered as of 3 Years Ago by
javaAddict,
Ezzaral
and
vchandra