Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting array of objects to array of comparable

Tags:

java

I've encountered a problem while doing a homework for online algorithms class. Casting Object[] to T[] where T is Comparable raises a run-time exception

public  static <T extends Comparable<? super T>> void mergeSort(T[] xs) {
    T[] aux = (T[]) new Object[xs.length];
    mergeSort(xs, aux, 0, xs.length);
}

I could rewrite it in C# which doesn't have any problems with creating generic arrays but I'd rather learn how to deal with this in Java.

like image 762
synapse Avatar asked Apr 12 '13 21:04

synapse


People also ask

How do you sort an array using comparable?

class Sort { private Integer[] intArray = {30,20,50,100,1,2,6,1,3,5}; Sort() { sortObject(intArray); } public <T extends Comparable<T>> void sortObject(T[] array) { T el = array[0]; for(T elements : array) { if(el. compareTo(elements)<0) { /// ?????? } }

Do arrays implement comparable?

The reason is that, the Arrays. sort(Object[]) method requires the object type to implement the Comparable interface so that the array can be sorted according to natural ordering of its elements.


2 Answers

If you're getting a runtime exception, it means that the objects you tried to cast don't acutally have that type. Language doesn't have anything to do with it. There's probably a bug in your code.

Edit: It sounds like you are confused by how Java's type system works. In C#, generics actually represent different types at runtime. In Java, generic types don't exist at runtime. They are only a convenience to enable better compile time type checking. During compilation, generics are replaced by a real type in a process known as type erasure.

Normally, the erasure of a generic type is Object, but since you provided an upper bound for T, it is converted to that bound, Comparable. Therefore, after erasure, your code looks like this.

Comparable[] aux = (Comparable[]) new Object[xs.length];

In otherwords, you're creating an array of type Object[] and immediately trying to cast it to type Comparable[]. Since Object doesn't implement Comparable, the types are incompatible, so you get a runtime exception. You can fix this by creating an array of Comparables instead.

public  static <T extends Comparable<? super T>> void mergeSort(T[] xs) {
    T[] aux = (T[]) new Comparable[xs.length];
    mergeSort(xs, aux, 0, xs.length);
}
like image 71
Antimony Avatar answered Oct 17 '22 10:10

Antimony


Try this:

public  static <T extends Comparable<? super T>> void mergeSort(T[] xs) {
    T[] aux = (T[])java.lang.reflect.Array.newInstance(xs.getClass().getComponentType(), xs.length);
    mergeSort(xs, aux, 0, xs.length);
}
like image 45
jdb Avatar answered Oct 17 '22 12:10

jdb