Hallo,
ich habe folgendes Problem. Die Sortierung habe ich geschafft. Beim binarySearch mit oder ohne comparator gibt es folgenden Abbruch.
java.lang.ClassCastException: java.lang.String cannot be cast to Person.
Hier der Code (Abbruch in 95).
ich habe folgendes Problem. Die Sortierung habe ich geschafft. Beim binarySearch mit oder ohne comparator gibt es folgenden Abbruch.
java.lang.ClassCastException: java.lang.String cannot be cast to Person.
Hier der Code (Abbruch in 95).
Java:
import java.util.Arrays;
import java.util.Comparator;
class PersonComparatorAuf implements Comparator<Person> {
public int compare(Person a1, Person b1) {
if (a1.getNachname() == b1.getNachname()) {
if (a1.getVorname().compareTo(b1.getVorname()) == 0) {
if (a1.getGeburtsjahr() < b1.getGeburtsjahr())
return -1;
else
return 1;
}
else {
return a1.getVorname().compareTo(b1.getVorname());
}
}
else if (a1.getNachname() == b1.getNachname()) {
return -1;
}
else {
return 1;
}
}
}
class PersonComparatorAb implements Comparator<Person> {
public int compare(Person a1, Person b1) {
if (a1.getNachname() == b1.getNachname()) {
if (a1.getVorname().compareTo(b1.getVorname()) == 0) {
if (a1.getGeburtsjahr() < b1.getGeburtsjahr())
return 1;
else
return -1;
}
else {
return (a1.getVorname().compareTo(b1.getVorname()) * -1);
}
}
else if (a1.getNachname() == b1.getNachname()) {
return 1;
}
else {
return -1;
}
}
}
class Person {
private String vorname, nachname;
private int geburtsjahr;
public Person(String nachname, String vorname, int geburtsjahr) {
this.vorname = vorname;
this.nachname = nachname;
this.geburtsjahr = geburtsjahr;
}
public String getVorname() {
return vorname;
}
public String getNachname() {
return nachname;
}
public int getGeburtsjahr() {
return geburtsjahr;
}
public String toString() {
return vorname + ", " + nachname + ". GJ: " + geburtsjahr;
}
}
public class SortPersonen {
public static void main(String[] args) {
Person[] arr = {
new Person("John", "Smith" , 1940),
new Person("John", "Black" , 1940),
new Person("John", "Black" , 1920),
};
print(arr);
//1.Bitte aufsteigend Sortieren (Nach Nachnamen, dann nach Vornamen, und dann nach dem Geburtsjahr
Comparator comparator = new PersonComparatorAuf();
Arrays.sort(arr, comparator);
print(arr);
//2. Mit binarySearch nach einer Person (John White, 1960) im Array suchen und Erg. ausgeben
int position = Arrays.binarySearch(arr, "John White 1960",comparator);
System.out.println("Suche1 = " + position);
//3. Mit binarySearch nach einer Person (John Black, 1940) im Array suchen und erg. ausgeben
//4. Das Array bitte absteigend sortieren (Arrays.sort) wie Aufgabe 1
Comparator comparator1 = new PersonComparatorAb();
Arrays.sort(arr, comparator1);
print(arr);
//5 Mit binarySearch nach einer Person (John Black, 1940) im Array suchen,
}
static void print(Person[] arr) {
for (Person person : arr) {
System.out.println(person);
}
}
}