Ich erhalte ClassCastException. Ich folgte dieser Antwort, verstand es aber nicht richtig. Cast Object to Generic Type for returning
BubbleSort.javaGenerische Klassenmethode, die einen Wert zurückgibt
import java.util.ArrayList;
import java.util.List;
public class BubbleSort<T extends Number> {
public List<T> list;
@SuppressWarnings("serial")
public BubbleSort() {
list = new ArrayList<T>() {
};
}
public void add(T obj) {
list.add(obj);
}
public void sort() {
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size() - 1; j++) {
if (list.get(j).intValue() > list.get(j + 1).intValue()) {
T swapElement = list.get(j);
list.set(j, list.get(j + 1));
list.set(j + 1, swapElement);
}
}
}
}
public <T> T getArray(Class<T> clazz){
T[] returnArray = (T[]) list.toArray();
return clazz.cast(returnArray);
}
}
MainPorgram.java
import java.lang.reflect.Array;
public class MainProgram {
public static void main(String args[]){
BubbleSort<Integer> bubbleSort = new BubbleSort<>();
bubbleSort.add(new Integer(1));
bubbleSort.add(new Integer(2));
bubbleSort.add(new Integer(6));
bubbleSort.add(new Integer(5));
bubbleSort.add(new Integer(4));
bubbleSort.add(new Integer(3));
Class<Integer[]> intArrayType = (Class<Integer[]>) Array.newInstance(Integer.TYPE, 0).getClass();
Integer[] sortedArray = (Integer[]) bubbleSort.getArray(intArrayType);
for(int i = 0 ; i < sortedArray.length; i++){
System.out.println(sortedArray[i]);
}
}
}
Console
Exception in thread "main" java.lang.ClassCastException: Kann nicht werfen [Ljava.lang .Objekt; [I bei java.lang.Class.cast (Unknown Source) bei BubbleSort.getArray (BubbleSort.java:32) bei MainProgram.main (MainProgram.java:15)
_ "hat es nicht richtig gemacht" _ ist ungenügend. Es wird erwartet, dass Sie den Stack-Trace veröffentlichen und angeben, welche Zeile in Ihrem Programm die Ausnahme auslöst. Erzählen Sie uns auch, was Sie getan haben, um das Problem zu beheben. Hast du den Code in deinem Debugger durchgegangen? –
Hier sind so viele Dinge falsch. – shmosel
'(BubbleSort.java:32)' Dies bedeutet, dass der Fehler in Zeile 32 von BubbleSort.java auftritt. Welche Linie ist das? –