I am trying to solve a exorcise that is supposed to learn me about the Comparable<T>
interface. It tells me to find the shortest and longest string in a string array.
I think I am supposed to make my own compareTo()
-method because the String.compareTo()
method sorts alphabetically. But I can't get what my method should look like.
This is my code so far:
class ComparableTest implements Comparable<String> {
public static void main(String[] args) {
String arr[] = {"hei", "hvordan", "gaar", "det", "med", "deg", "a"};
String tempSto = arr[0]; //long string
String tempLit = arr[0]; //short string
for(String e : arr) {
if(e.compareTo(tempSto) > 0) {
tempSto = e;
}
if(e.compareTo(tempLit) < 0) {
tempLit = e;
}
}
System.out.println("Longest string is: " + tempSto);
System.out.println("Shortest string is: " + tempLit);
}
}