Code: Select all
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>
CODE des Klassenautos: < /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
Code: Select all
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>
Die Klasse 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;
}
}
}
}
Aber ich bin immer noch verwirrt, da ich immer noch neu im Konzept des vergleichbaren und vergleichbaren Vergleichs bin (ich kenne den Unterschied zwischen beiden) < /p>
Kann jemand erklären, ob der Code aufgrund der Umstände selbst oder eines anderen Grundes anders geschrieben ist, und wie hat der Code die Methode automatisch "vergleiche" () und "komparieren" () () () '' '' '', '' ',' '' '', '' ',' '' '', '' ',' '', '' ',' '' ',' '' ',' '' ',' '' ',' '' ',' '', '' '' ',' '' ',' '' '', '' und '' '' '' ', ohne die Funktion selbst zu rufen? Ich muss wirklich wissen, wie diese Konzepte in diesem Code funktionieren, und eine ausführliche Erklärung für einen Neuling wäre hilfreich. Danke!