Код: Выделить всё
public class Main {
public static void main(String[] args) {
// Create a list of cars
ArrayList myCars = new ArrayList();
myCars.add(new Car("BMW", "X5", 1999));
myCars.add(new Car("Honda", "Accord", 2006));
myCars.add(new Car("Ford", "Mustang", 1970));
// Sort the cars
Collections.sort(myCars);
< /code>
Class Car's Code: < /p>
class Car implements Comparable {
public String brand;
public String model;
public int year;
public Car(String b, String m, int y) {
brand = b;
model = m;
year = y;
}
// Decide how this object compares to other objects
public int compareTo(Object obj) {
Car other = (Car)obj;
if(year < other.year) return -1; // This object is smaller than the other one
if(year > other.year) return 1; // This object is larger than the other one
return 0; // Both objects are the same
Мы видим другое поведение для компаратора:
Код: Выделить всё
public class Main {
public static void main(String[] args) {
ArrayList myNumbers = new ArrayList();
myNumbers.add(33);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(34);
myNumbers.add(8);
myNumbers.add(12);
Comparator myComparator = new SortEvenFirst();
Collections.sort(myNumbers, myComparator);
for (int i : myNumbers) {
System.out.println(i);
< /code>
класс sortevenfirst (): < /p>
class SortEvenFirst implements Comparator {
public int compare(Object obj1, Object obj2) {
// Make sure the objects are integers
Integer a = (Integer)obj1;
Integer b = (Integer)obj2;
// Check each number to see if it is even
// A number is even if the remainder when dividing by 2 is 0
boolean aIsEven = (a % 2) == 0;
boolean bIsEven = (b % 2) == 0;
if (aIsEven == bIsEven) {
// If both numbers are even or both are odd then use normal sorting rules
if (a < b) return -1;
if (a > b) return 1;
return 0;
} else {
// If a is even then it goes first, otherwise b goes first
if (aIsEven) {
return -1;
} else {
return 1;
}
}
}
}
Из моего понимания в сравнимом примере было несколько удобным, что они могли включать в себя оба объекта Cars, а также метод /emefet (Emefot emefet (Emefot emefet (Emefot emefet (Emefot emefet (Emefot emefet (Emefot eme>/Emefeto. Но я все еще смущен, так как я все еще новичок в концепции сопоставимого и компаратора (я даже не знаю разница между обоими) < /p>
, так что кто -то может объяснить, написан ли код по -разному из -за обстоятельств или другой причины, а также того, как код автоматически выполнил метод «сравнение ()» и «compare ()», а также сама вызов функции? Мне действительно нужно знать, как эти концепции работают в этом коде, и было бы полезно углубленное объяснение новичка. Спасибо!
Подробнее здесь: https://stackoverflow.com/questions/794 ... comparator