12 Replies Latest reply on Dec 3, 2008 4:50 AM by 800298

    Comparator without a method to compare?

      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?


      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!