I am getting ClassCastException. I was following this answer but did not get it right.
Cast Object to Generic Type for returning
BubbleSort.java
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: Cannot cast [Ljava.lang.Object; to [I at java.lang.Class.cast(Unknown Source) at BubbleSort.getArray(BubbleSort.java:32) at MainProgram.main(MainProgram.java:15)