Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Creating a Custom Comparator 1

Status
Not open for further replies.

brinker

Programmer
May 31, 2001
48
CA
Hi,

I have been trying to figure out how to create a custom comparator that I can use to handle a list of items of a user defined data type. For instance:

class mytype
{
int a;
String b;
String c;
URL d;
}

If I want a comparator that can order these items by int a, how could I construct it...and use it. I know that there must be a way as Java has a Comparator interface.

thanks

Brinker
 
You could write a quick compare method inside your mytype class like so:
Code:
public int compare(int comparee){
   if(comparee > a){
      return 1;
   }
   if(comparee = a){
      return 0;
   }
   if(comparee < a){
      return -1;
   }
}

Just a thought
-Tarwn --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
 
when comparing int members your comparator implementation needs to have:
Code:
public int compare(Object o1, Object o2) {
  mytype mt1 = (mytype)o1;
  mytype mt2 = (mytype)o2;
  return (mt1.a - mt2.a);
}
Its as simple as that for int members.

For String members, you should use something like:
Code:
public int compare(Object o1, Object o2) {
  mytype mt1 = (mytype)o1;
  mytype mt2 = (mytype)o2;
  return (mt1.b.compareTo(mt2.b));
}

You can even make your comparator sort on an int, and then a string using:
Code:
public int compare(Object o1, Object o2) {
  mytype mt1 = (mytype)o1;
  mytype mt2 = (mytype)o2;
  int ret = mt1.a - mt2.a;
  if(ret != 0)
    return ret;
  else
    return (mt1.b.compareTo(mt2.b));
}

etc.. Hope this helps :)


 
Any Tips on how to make a comparator to compare float numbers? I believe that maybe just multiplying the numbers by 10E5 might be the way, but it is not too efficient.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top