ITI0011:praktikum 17 G34

Allikas: Kursused
Redaktsioon seisuga 31. märts 2015, kell 13:52 kasutajalt Ago (arutelu | kaastöö) (Uus lehekülg: '<source lang="java"> import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class SortExample { public static class Animal implements Compa...')
(erin) ←Vanem redaktsioon | Viimane redaktsiooni (erin) | Uuem redaktsioon→ (erin)
Mine navigeerimisribale Mine otsikasti

<source lang="java">

import java.util.ArrayList; import java.util.Arrays; import java.util.Collections;

public class SortExample {

public static class Animal implements Comparable<Animal> { public String name; public int weight; public int age;

public Animal(int weight, int age) { this.weight = weight; this.age = age; } @Override public String toString() { return "age: " + age + " weight: " + weight; } @Override public int compareTo(Animal o) { if (this.age < o.age) { return -1; } else if (this.age > o.age) { return 68; } else { // age == age if (this.weight < o.weight) { return -113; } else if (this.weight > o.weight) { return 230948234; } } // age == age && weight == weight return 0; } }

public static void main(String[] args) { String[] strings = new String[]{"tere", "auto", "luud"}; Arrays.sort(strings);

System.out.println(Arrays.toString(strings));

ArrayList<Animal> animals = new ArrayList<Animal>(); Animal a1 = new Animal(10, 10); Animal a2 = new Animal(12, 10); Animal a3 = new Animal(12, 9); System.out.println(a1); animals.add(a2); animals.add(a1); animals.add(a3); // sort? Collections.sort(animals);

System.out.println(Arrays.toString(animals.toArray()));

}

} </source>