2

I have both a Dog and Cat class which look something like this:

public class Dog implements Speakable
{
private String name;

public Dog(String name)
{
    this.name = name;
}

public void speak()
{
    System.out.println("Woof! Woof!");
}

public String toString()
{
    return "Dog: " + name;
}

}

These classes both implement an interface I have created called Speakable which looks like this:

public interface Speakable
{
  public void speak();
}

This Speakable interface exists because I need a reference variable that allows me to add Dogs and Cats to the same ArrayList and still invoke the speak() method on them.

I also need to override the compareTo() method of the Comparable interface so I can compare the names of dogs. When calling this method, I think my code will look like this: a.compareTo(b). I want this new method to return -1 if a is greater than b, 1 if a is less than b, and 0 if they are equal.

I think I need the Dog class to specifically implement Comparable in addition to Speakable so the Comparable interface I have written is this:

public interface Comparable<Dog>
{
    public int compareTo(Object obj);
}

How do I override the compareTo() method to meet the needs I listed above? I know I will need several if statements, but I can't think of a way to write this without calling the compareTo() method within the new compareTo() method. Is that legal? Shouldn't the compareTo() method from the comparable interface already contain these decisions?

JoeSchmuck
  • 101
  • 3
  • 8
  • "How do I override the compareTo() method to meet the needs I listed above" - what are your needs. I can see that you want to compare only name – Rahman Oct 08 '15 at 14:27
  • What do you mean by `a is greater than b, a is less than b`? How do you compare `dog`s? – TDG Oct 08 '15 at 14:27
  • 1
    You are trying to sort your List ? Or a List ? – James Wierzba Oct 08 '15 at 14:27
  • 1
    You are not supposed to create your own `Comparable` interface. That's why it's generic - each class can implement it for itself. – RealSkeptic Oct 08 '15 at 14:28

2 Answers2

3

Remove your custom Comparable, and use the Java Comparable<T>. And you could modify Speakable to extend Comparable. Something like,

public interface Speakable extends Comparable<Speakable>

Then every Speakable is also a Comparable<Speakable>

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

Use Java Comparable interface in Dog class. Somenthing like this:

public class Dog implements Speakable, Comparable<Dog>{
    @Override
    public int compareTo(Dog o) {
        return this.name.compareTo(o.name);
    }

}

ocastillo
  • 21
  • 3