Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClassCast Exception in java, cannot cast to Ljava.lang.Integer

Tags:

java

I am trying to use java generics-

 public T[] toArray()
   {


      T[] result = (T[])new Object[numberOfEntries]; 

       // some code here to fill the resultarray



     return result;
   } // end toArray

Now in my main funciton, this is what I am doing-

        A<Integer> obj= new A<Integer> ();

        obj.add(1); //add method not shown here as it is not relevant to question
        obj.add(2);
        obj.add(3);
        obj.add(4);


        Integer arr[] = (Integer[]) obj.toArray();

I get the following error-

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
    at tester.main(tester.java:14)

How can I fix this?


2 Answers

You are trying to cast an object of type Object[] to Integer[]. These are incompatible types so the JVM throws a ClassCastException. You need to provide some runtime type information to toArray, for example like this:

public T[] toArray(Class<T> clazz)
{
  @SuppressWarnings("unchecked")
  T[] result = (T[])Array.newInstance(clazz, numberOfEntries);
  // some code here to fill the resultarray
  return result;
}

...

// and use it like this:
Integer arr[] = obj.toArray(Integer.class);
like image 53
Tamas Hegedus Avatar answered May 15 '26 22:05

Tamas Hegedus


Due to type erasure, the toArray() method will return an array of type Object[], not Integer[], and it is not possible to cast Object[] to Integer[].

If you want to return an Integer array at runtime from your generic class, you can try passing in the actual class type as a parameter to the toArray() method:

public T[] toArray(Class<T> c, int size) {
    @SuppressWarnings("unchecked")
    final T[] result = (T[]) Array.newInstance(c, s);
    return result;
}

Usage:

A<Integer> obj= new A<Integer> ();

obj.add(1);
obj.add(2);
obj.add(3);
obj.add(4);

Integer[] arr = obj.toArray(Integer.class, obj.size());
like image 25
Tim Biegeleisen Avatar answered May 15 '26 21:05

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!