File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Sorting by string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Sorting by string" Watch "Sorting by string" New topic
Author

Sorting by string

Lance Gray
Greenhorn

Joined: Dec 06, 2011
Posts: 20
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

Joined: Jan 03, 2004
Posts: 6109
    
    6

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

Joined: Dec 06, 2011
Posts: 20
Thanks. I changed the code to this one and it worked.

 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Sorting by string
 
Similar Threads
Scanning a text file
LinkedList of objects
never satisfied with polymorphism
Problem with the Scriptless JSps Page 378 question (Code Magents) from the Head First book 1st edt
Spellcheck with pronounciation words