Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast Object to Comparable in java

Here we have generic method:

public static <T extends Comparable<T>> T[] function(T[] a)
{
    Object[] m = new Object[2];

    /* some work here */

    return (T[]) m;
}

A ClassCastException is thrown . What's wrong with it?

like image 322
Majid Azimi Avatar asked Jun 30 '11 14:06

Majid Azimi


1 Answers

An array of Object is not an array of any subclass of Object. You are facing one of the limitations of generics in Java: you cannot create a generic array. See this thread for an approach that does work.

like image 193
Ted Hopp Avatar answered Sep 29 '22 08:09

Ted Hopp