fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import java.util.Collections;
  9.  
  10. class Person implements Comparable<Person> {
  11. private int salary;
  12. private String name;
  13.  
  14. public Person(String name, int salary) {
  15. this.name = name;
  16. this.salary = salary;
  17. }
  18.  
  19. public String getName() {
  20. return name;
  21. }
  22.  
  23. public int getSalary() {
  24. return salary;
  25. }
  26.  
  27. @Override
  28. public String toString() {
  29. return name + " " + salary;
  30. }
  31.  
  32. @Override
  33. public int compareTo(Person person){
  34. if (this.salary == person.getSalary())
  35. return 0;
  36. else if (this.salary < person.getSalary())
  37. return 1;
  38. else return -1;
  39. }
  40. }
  41.  
  42. /* Name of the class has to be "Main" only if the class is public. */
  43. class Ideone
  44. {
  45.  
  46. public static void main(String[] args) {
  47. List<Person> people = new ArrayList<Person>();
  48. people.add(new Person("Matti", 150000));
  49. people.add(new Person("Pekka", 3000));
  50. people.add(new Person("Mikko", 300));
  51. people.add(new Person("Arto", 10));
  52. people.add(new Person("Merja", 500));
  53. people.add(new Person("Pertti", 80));
  54. System.out.println(people);
  55. /*
  56.   * When you have implemented the compareTo-method, remove comment below.
  57.   */
  58. Collections.sort(people);
  59. System.out.println(people);
  60. }
  61. }
Success #stdin #stdout 0.09s 27852KB
stdin
Standard input is empty
stdout
[Matti 150000, Pekka 3000, Mikko 300, Arto 10, Merja 500, Pertti 80]
[Matti 150000, Pekka 3000, Merja 500, Mikko 300, Pertti 80, Arto 10]