This discussion is archived
12 Replies Latest reply: Dec 2, 2008 8:50 PM by 800298 RSS

Comparator without a method to compare?

843785 Newbie
Currently Being Moderated
Hey all,

I was looking at the examples of comparator and implementing them; however, what do you do when the class that parameterized with does not have a method such as getAge, getName?

Example:

Main class - Fruit: methods: Fruit constructor, toString, compareTo
Subclasses - Apple, Orange: methods: Apple/Orange constructor, toString

What do you do in this case? Can you call in a variable and compare it to that?

I thought about doing this:
     public int compare(Fruit fruit1, Fruit fruit2){
          if (fruit2.getName() == fruit1.getName())
               return fruit2.compareTo(fruit1);
          return (fruit2.getName() < fruit1.getName()) ? -1 : 1;
But it doesn't really make sense because I'm trying to call in a nonexistent method. I haven't seen an example without one of the methods: getName, getAge, getNumber, etc.

Any help would be greatly appreciated!