How do you implement the Comparable interface inside of a custom class?

Hello,

Thanks for taking the time to help.  Allow me to explain the situation:

I have a "dog" class.  Somehow, I need to create a subclass that extends the java's "Comparable" class so that "dog"s can be compared.  

The reason I need to do this is because I have a tree that is going to be built up of dogs.  However, the tree's "find" feature needs to be able to access the Comparable "something (i dont know what you would call this)" in order to traverse the tree.

So, can someone please explain to me how I would go about implementing the Comparable "(something, i think you cal it a subclass?)" into my "dog" class so that I can achieve my desired outcome?


Thanks for the help,

an aspiring java learner
alexthecodepoetAsked:
Who is Participating?
 
Ajay-SinghConnect With a Mentor Commented:
public class Dog implements Comparable<Dog> {
    private String m_name;

    public int compareTo(Dog o) {
        return m_name.compareTo(o.m_name); // assuming that you want to compare based on name        
    }
}
0
 
CEHJConnect With a Mentor Commented:
What aspect(s) of dog are you comparing on. The name? If so

public int compareTo(Object other) {
    return name.compareTo((Dog)other).name);
}
0
 
alexthecodepoetAuthor Commented:
Awesome, these are perfect!!

Thanks guys, especially for your timeliness.  

I appreciate the help very very much!
0
 
CEHJCommented:
:-)
0
 
alexthecodepoetAuthor Commented:
Hi Guys,

I posted a followup question, perhaps you can help?

Thanks

http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_22076950.html
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.