import java.util.Arrays; public class ObjectVergleich { public static void main(String[] args) { Moped m1 = new Moped("BMW", "RS 54", 58); Moped m2 = new Moped("Moto Guzzi", "Falcone Sport", 23); Moped m3 = new Moped("AJS", "7R", 45); Moped m4 = new Moped("Moto Guzzi", "V8", 72); Moped m5 = new Moped("Böhmerland", "Tourer", 16); Moped m6 = new Moped("Moto Guzzi", "Falcone Tourismo", 19); Moped[] moped = { m1, m2, m3, m4, m5, m6 }; Arrays.sort(moped); for (Moped m : moped) { if (m != null) { System.out.println(m.toString()); } } } } class Moped implements Comparable { String hersteller; String typ; int ps; public Moped(String hersteller, String typ, int ps) { this.hersteller = hersteller; this.typ = typ; this.ps = ps; } public int compareTo(Object m) { if (this == (Moped) m) { return 0; } if (m instanceof Moped) { Moped einMoped = (Moped) m; if (this.getHersteller() == null) { return 1; } if (einMoped.getHersteller() == null) { return -1; } if (this.getHersteller().equals(einMoped.getHersteller())) { if (this.getTyp() == null) { return 1; } if (einMoped.getTyp() == null) { return -1; } if (this.getTyp().equals(einMoped.getTyp())) { return this.getPS() - einMoped.getPS(); // Vorsicht! } return this.getTyp().compareTo(einMoped.getTyp()); } return this.getHersteller().compareTo(einMoped.getHersteller()); } return -1; } public String getHersteller() { return hersteller; } public String getTyp() { return typ; } public int getPS() { return ps; } @Override public String toString() { return "Moped [ Hersteller:" + getHersteller() + " Typ:" + getTyp() + " PS:" + getPS() + " ]"; } }