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