I have:
List alphabet; (contains 26 unique characters as elements, for example
qwertyuiosapdfghjklzcxvbnm)
List wordsToArrange; contains words as elements, for example:
- apple
- stream
- posthouse
- sea
- seed
I need to arrange the words according to the alphabet i have made.
My approach at the moment is with for cycles.
alphabet(i) compare it with all the words charAt(0)
if only 1 is found i put it to a new list arrangedList
but if 2 is found i go alphabet(i+1) till the letter is found and now i can put them in a right order to arrangedList....
then move back to alphabet(i+1) till alphabet(26) and now all should be arranged correctly...
I have wrote some base for this code but i wanted to ask what would be other approaches before i start the serious "for cyclying".
Thanks!
解决方案
What about wrapping the String in a new Class that implements comparable?
May be some edge case bugs that i have not tested.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CompString {
public static void main(String[] args) {
List list = new ArrayList();
list.add(new ComparableString("apple"));
list.add(new ComparableString("stream"));
list.add(new ComparableString("posthouse"));
list.add(new ComparableString("sea"));
list.add(new ComparableString("seed"));
Collections.sort(list);
System.out.println(list);
}
}
class ComparableString implements Comparable {
String str;
static String sortOrder = "qwertyuiosapdfghjklzcxvbnm";
public ComparableString(String string) {
str = string;
}
@Override
public String toString() {
return str;
}
@Override
public int compareTo(ComparableString other) {
for (int i = 0; i < Math.min(this.str.length(), other.str.length()); i++) {
int thisOrder = ComparableString.sortOrder.indexOf(this.str.charAt(i));
int thatOrder = ComparableString.sortOrder.indexOf(other.str.charAt(i));
int order = thisOrder - thatOrder;
if (order != 0) {
return order;
}
}
if (this.str.length() > other.str.length()) {
return -1;
} else if (this.str.length() < other.str.length()) {
return 1;
}
return 0;
}
}