ITI0011:praktikum 17 G5
<source lang="java">
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections;
public class SortExample {
public static class Person implements Comparable<Person> { private String name; private int age; private int height; public Person(int age, int height) { this.age = age; this.height = height; } @Override public String toString() { return "person age: " + age + " height:" + height; }
@Override public int compareTo(Person o) { if (this.age < o.age) { return -10; } // elseif if (this.age > o.age) { return 10; } // else // this.age == o.age if (this.height < o.height) return -6; if (this.height > o.height) return 9; // this.height == o.height return 0;
}
}
public static void main(String[] args) { Person p1 = new Person(10, 110); Person p2 = new Person(10, 90); Person p3 = new Person(8, 90); ArrayList<Person> persons = new ArrayList<Person>(); persons.add(p1); persons.add(p2); persons.add(p3);
Collections.sort(persons);
for (Person p : persons) { System.out.println(p); //System.out.println(p.age + " " + p.height); } /* ArrayList<String> strings = new ArrayList<String>(); strings.add("tere"); strings.add("aabits"); strings.add("elevant"); */ String[] strings = new String[]{"tere", "aabits", "elevant"}; // strings[0] = "tere"; // sort? Arrays.sort(strings);
for (String s : strings) { System.out.println(s); }
}
}
</source>