fork download
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3.  
  4. public class Animal implements Comparable<Animal> {
  5.  
  6. private String name;
  7.  
  8. public Animal(String name) {
  9. this.name = name;
  10. }
  11.  
  12. public String toString() {
  13. return name;
  14. }
  15.  
  16. @Override
  17. public int compareTo(Animal that) {
  18. // compare the two animal objects by name
  19. return this.name.compareTo(that.name);
  20. }
  21.  
  22. public static void main(String[] args) {
  23.  
  24. ArrayList<Animal> animals = new ArrayList<Animal>();
  25. animals.add(new Animal("Zed"));
  26. animals.add(new Animal("Diesel"));
  27. animals.add(new Animal("Garfield"));
  28.  
  29. System.out.println("Animals before sort: ");
  30. System.out.println(animals);
  31.  
  32. Collections.sort(animals);
  33. System.out.println("Animals after sort: ");
  34. System.out.println(animals);
  35. }
  36.  
  37. }
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty