Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting by string

 
Lance Gray
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a class called Dictionary. Now inside the Dictionary class, there are objects called Word. Each Word object has a method called getWord() that returns a String. Each Word object is placed in an ArrayList called DictionaryEntries. Now my problem is, I need to sort the Word objects inside DictionaryEntries using the string that the method getWord() returns. How do I do this?

I tried this one that I have used before but it's only for integers and not Strings.



Thanks in advance.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Either, have Word implement Comparable<Word>, or else define a new class that implements Comparator<Word>. Either way, the compareTo()/compare() method will call String1.compareTo(String2) on the Words' respective Strings.

Google for java comparable comparator example or java comparable comparator tutorial for details and examples.
 
Lance Gray
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. I changed the code to this one and it worked.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic