3

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?

4 Answers 4

5

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);
Sign up to request clarification or add additional context in comments.

Comments

4

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());

Comments

0

Object[] cannot cast to Integer[] directly. Use below code to move elements one by one:

    Object[] arr = new Object[SIZE];
    Integer[] arr1 = new Integer[arr.length];
    int i = 0;
    for(Object a:arr){
        arr1[i++] = (Integer)a;
    }

Comments

0

You have this line in code T[] result = (T[])new Object[numberOfEntries]; You need to replace it with T[] result = (T[])new T[numberOfEntries];

2 Comments

I suppose you cannot say new T[] - have you tried that?
Generic T can not be instantiated directly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.