ITI0011:praktikum 17 G12

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

<source lang="java">

import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;

public class SortExample {

public static class CarComparator implements Comparator<Car> {

@Override public int compare(Car c1, Car c2) { // if c1 == c2? if (c1.name.equals(c2.name) && c1.maxSpeed == c2.maxSpeed) return 0;

// if c1 < c2? if (c1.name.equals(c2.name)) { if (c1.maxSpeed > c2.maxSpeed) { // if c1 < c2 return 1; } else { // if c1 > c2 return -1; } } else { // name != name return c1.name.compareTo(c2.name); } }

}

public static void main(String[] args) {

ArrayList<String> strings = new ArrayList<String>(); strings.add("tere"); strings.add("aabits"); Collections.sort(strings);

Car c1 = new Car("audi", 100); Car c2 = new Car("audi", 200); Car c3 = new Car("bmw", 100);

ArrayList<Car> cars = new ArrayList<Car>(); cars.add(c3); cars.add(c2); cars.add(c1);

//Collections.sort(list, c); Collections.sort(cars, new CarComparator());

// sort? for (Car c : cars) { System.out.println(c); } }

}

</source>