Reputation: 21
I need to take a set of strings given at the command line and use the comparable interface to order them at first by length and, in the case of a tie, lexiographical order.
The first thing I'm having trouble with is grouping the words given at the command line without using an array. Then I need a pointer on how to order them by length...
the way I have my program setup is: 1. class 'stringy' with a main method 2. Class 'LengthSortableString' which implements comparable and has a constructor that takes a string argument. Also has a getContents method which returns a string and has no arguments, as well as the compareTo method.
thanks for any help
Upvotes: 0
Views: 96
Reputation: 425033
Without writing code...
Use a Set<String>
to hold the words - just add()
them to it.
When it comes time to order them, create a List<String>
and addAll()
the set.
Use Colllections.sort()
with a custom Comparator<String>
, whose compare()
method makes the comparison you describe; if the two Strings have the same length, return the comparison between the two Strings, otherwise return the comparison of the lengths.
If the input won't ever contain duplicates, you can skip the Set and use a List from the start.
Upvotes: 1