fork download
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.List;
  4.  
  5. class Test {
  6. String arr[] = {"hei", "hvordan", "gaar", "det", "med", "deg", "a"};
  7.  
  8. /**
  9.   * Use composition.
  10.   */
  11. class MyComparableString implements Comparable<MyComparableString> {
  12. String myString;
  13.  
  14. MyComparableString(String s) {
  15. myString = s;
  16. }
  17.  
  18. @Override
  19. public int compareTo(MyComparableString other) {
  20. // Compare the lengths of the strings in this and other.
  21. Integer l1 = myString.length();
  22. Integer l2 = other.myString.length();
  23. return l1.compareTo(l2);
  24. }
  25.  
  26. // String representation.
  27. public String toString() {
  28. return myString;
  29. }
  30. }
  31.  
  32. void go() {
  33. // Convert the String array into a List (Collection) of MyComparableString.
  34. List<MyComparableString> l = new ArrayList<>();
  35. for (String s: arr) {
  36. l.add(new MyComparableString(s));
  37. }
  38. // Print longest and shortest.
  39. System.out.println("Shortest: " + Collections.min(l));
  40. System.out.println("Longest: " + Collections.max(l));
  41. }
  42.  
  43. public static void main(String[] args) {
  44. new Test().go();
  45. }
  46. }
Success #stdin #stdout 0.11s 320576KB
stdin
Standard input is empty
stdout
Shortest: a
Longest: hvordan