This discussion is archived
14 Replies Latest reply: Jun 27, 2007 3:55 PM by 807605 RSS

Creating a compareTo method for a Word class

807605 Newbie
Currently Being Moderated
NOTE: This is for a homework assignment!
=====================================================
I created a class called Word. The Word class holds a String and an integer. I need a compareTo method that works for this specific class. I was told by a friend that I needed to implement the Comparable interface, but I am not sure that is needed.
  • 1. Re: Creating a compareTo method for a Word class
    807605 Newbie
    Currently Being Moderated
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html

    You implement that interface, then define how Words are compared in the compareTo method. It's up to you how you define that.
  • 2. Re: Creating a compareTo method for a Word class
    800323 Newbie
    Currently Being Moderated
    http://www.java-tips.org/java-se-tips/java.lang/how-to-use-comparable-interface.html
    http://www.javaworld.com/javaworld/jw-12-2002/jw-1227-sort.html
  • 3. Re: Creating a compareTo method for a Word class
    807605 Newbie
    Currently Being Moderated
    You implement that interface, then define how Words
    are compared in the compareTo method. It's up to you
    how you define that.
    Yep.
    eg
    public class Word implements Comparable{
         
         public String s;
         public int i;
         
         public int compareTo(Object o) {
              if (o instanceof Word) {
                   Word w = (Word)o;
                   if (w.s.equals(s) && w.i == i)
                        return 1;
              }
              return 0;
         }
    
    }
  • 4. Re: Creating a compareTo method for a Word class
    807605 Newbie
    Currently Being Moderated
    You implement that interface, then define how
    Words
    are compared in the compareTo method. It's up to
    you
    how you define that.
    Yep.
    eg
    public class Word implements Comparable{
         
         public String s;
         public int i;
         
         public int compareTo(Object o) {
              if (o instanceof Word) {
                   Word w = (Word)o;
                   if (w.s.equals(s) && w.i == i)
                        return 1;
              }
              return 0;
         }
    
    }
    I think you need to read the description of compareTo again:
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html#compareTo(T)
  • 5. Re: Creating a compareTo method for a Word class
    807605 Newbie
    Currently Being Moderated
    Hi hughveal:

    If you plan to make a manual comparison of your Word objects, then
    you do not need to implement the Comparable interface, nor you need
    a compareTo method, you could use any other method for that purpose.

    But if you plan to make a list (e.g. ArrayList<Word>) of Words, and then have
    them sorted.

    You have two choices.
    A) Follow your friend's advice, which is correct, implement the Comparable
    interface which will force you to implement the compareTo method, and
    when Sorting (e.g. using, Collections.sort(yourList)) will be sorted using
    your compareTo method implemented.
    //if you are using java 5 or later
    public class Word implements Comparable<Word>{
       ... your code ...
    
       public int compareTo(Word obj){
          ...compare logic...
       }
    }
    
    //if you are using java 1.4
    public class Word implements Comparable{
       ... your code ...
    
       public int compareTo(Object obj){
         //check using   instanceof    , and do respective casts
          ...compare logic...
       }
    }
    
    //in other code
    ArrayList<Word> x = new ArrayList<Word>;
    x.add(new Word("Hi", 5)); 
    x.add(new Word("World", 8));
    
    Collections.sort(x);
    B) you could sort, and make an Anonymous class of Comparator to sort
    ArrayList<Word> x = new ArrayList<Word>;
    x.add(new Word("Hi", 5)); 
    x.add(new Word("World", 8));
    
    //Java 5 case
    Collections.sort(x, new Comparator<Word>(){
         public int compare(Word o1, Word o2){
              ...comparing logic...
         }
    });
    
    
    //Java 1.4 case
    Collections.sort(x, new Comparator(){
         public int compare(Object o1, Object o2){
              //check using   instanceof    , and do respective casts
              ...comparing logic...
         }
    });
    Hope this helps, cya around.
  • 6. Re: Creating a compareTo method for a Word class
    807605 Newbie
    Currently Being Moderated
    Well I am inserting instances of this Word type into a Binary Search Tree. Here is my code so far:
    /*
    Word class 
    
    */
    
    public class Word implements Comparable
    {
         private String Phrase;
         private int counter;
         
    //Empty Constructor
         public Word()
              {
                   Phrase = null;
                   counter = 0;
              }
         
    //constructor with 2 arguments
         public Word(String phr, int cnt)
         {
              Phrase = phr;
              counter = cnt;
         }
    //Constructor with one argument
         public Word(String phr)
         {
              Phrase = phr;
              counter = 0;
         }
    
    //equals() method
         public boolean equals(Word looking)
         {
              boolean status;
              
              if(Phrase.equals(looking.Phrase)&& (counter != looking.counter))
                   status = true;
              else
                   status = false;
              return status;
         }
    
    
    
    //compareTo method
    
    
    //toString method
         public String toString()
         {
              String describer = Phrase + ", " + counter;
              return describer;
         }
    //setPhrase
         public void setPhrase(String p)
         {
              Phrase = p;
         }
    
    //setCount
         public void setCount(int c)
         {
              counter = c;
         }
    
    //getword
         public String getWord()
         {
              return Phrase;
         }
    
    //getcount
         public int getCount()
         {
              return counter;
         }
         
         
    //incword
    public int incword()
    {
         counter++;
    }
    
    //decword
    public int decword()
    {
         counter--;
    }     
    }
         
    Any idea if I am on the right track?
  • 7. Re: Creating a compareTo method for a Word class
    807605 Newbie
    Currently Being Moderated
    Any idea if I am on the right track?
    Pretty much. The question is, how do you want to define if a Word is less than, equal to, or greater than another Word? How would you describe it in English? Is it dependent on just the String, or does it take the int into account too?
  • 8. Re: Creating a compareTo method for a Word class
    807605 Newbie
    Currently Being Moderated
    The String is an actual word read in from a file and placed into a Binary Search Tree. The int is the count of the number of times the word appears in the sentence.
  • 9. Re: Creating a compareTo method for a Word class
    807605 Newbie
    Currently Being Moderated
    The String is an actual word read in from a file and
    placed into a Binary Search Tree. The int is the
    count of the number of times the word appears in the
    sentence.
    Ok, but how do you order Words based on that info? Which comes first: [Hello, 4] or {World, 7] ?
  • 10. Re: Creating a compareTo method for a Word class
    807605 Newbie
    Currently Being Moderated
    Since they are being inserted into a Binary Search Tree, I use an addelement method from a Binary Search Tree class. So to answer your question first come, first serve.
  • 11. Re: Creating a compareTo method for a Word class
    807605 Newbie
    Currently Being Moderated
    I tried some code but it doesn't work.
    //compareTo method
         public int compareTo(Word comp)
         {
              if (comp.Phrase == ((Word) comp).Phrase)
                   return 0;
              else if ((comp.Phrase) > ((Word) comp).Phrase)
                   return 1;
              else
                   return -1;
    
    
         
         
         
         }
    Errors:
    Word.java:6: Word is not abstract and does not override abstract method compareTo(java.lang.Object) in java.lang.Comparable
    public class Word implements Comparable
           ^
    Word.java:50: operator > cannot be applied to java.lang.String,java.lang.String
              else if ((comp.Phrase) > ((Word) comp).Phrase)
                                     ^
    2 errors
  • 12. Re: Creating a compareTo method for a Word class
    807605 Newbie
    Currently Being Moderated
    Ok, respecting only the compareTo

    First of all, Strings are not compared as numbers using "==", ">", "<", etc.
    of all of those, only "==" will compile and you are comparing String references,
    and not String values.

    You have two possibilites now.
    A) If you are using Java 1.4, the compare to definition should be:
    public int compareTo(Object comp){
         return comp.Phrase.compareTo( ((Word)comp).Phrase );
    }
    B) If you are using Java 5, and your class implementation is Templeted
    public int compareTo(Word comp){
         //No cast, and, be careful to use "this" if using the paramenter name same as the variable name
         return this.comp.Phrase.compareTo( comp.Phrase ); 
    }
  • 13. Re: Creating a compareTo method for a Word class
    807605 Newbie
    Currently Being Moderated
    public int compareTo(Object comp){
    return comp.Phrase.compareTo( ((Word)comp).Phrase
    e );
    }
    Is that the entire method?
  • 14. Re: Creating a compareTo method for a Word class
    807605 Newbie
    Currently Being Moderated
    Yes, because if you look at the Java API, String already has a compareTo method, so just use it.