fork download
  1. import java.util.*;
  2.  
  3. class Cat implements Comparable<Cat>
  4. {
  5. int age;
  6.  
  7. Cat(int age)
  8. {
  9. this.age = age;
  10. }
  11.  
  12.  
  13. public int compareTo(Cat other)
  14. {
  15. if (this.age < other.age)
  16. return -1;
  17. else if (this.age == other.age)
  18. return 0;
  19. else
  20. return 1;
  21. }
  22.  
  23. }
  24.  
  25. class Tester
  26. {
  27. public static void main(String args[])
  28. {
  29. // list of cats.
  30. List<Cat> list = new ArrayList<Cat>();
  31. list.add(new Cat(5));
  32. list.add(new Cat(1));
  33. list.add(new Cat(6));
  34. list.add(new Cat(7));
  35. list.add(new Cat(3));
  36.  
  37. //Collections.sort() automatically sorts the list using our compareTo() method.
  38. Collections.sort(list);
  39.  
  40. //print sorted age list.
  41. for(Cat cat: list)
  42. System.out.print(cat.age + ", ");
  43. }
  44. }
Success #stdin #stdout 0.07s 380160KB
stdin
Standard input is empty
stdout
1, 3, 5, 6, 7,