1

I don't know what to do about my generic array. I keep getting this error

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;

the error is related to this bit of code

T[] a = (T[]) new Object[temp];

My class extends comparable, and I don't know why I keep getting this error. Any hints on how to fix this will be greatly appreciated. Here is the code.

public void balance()
 {
  int temp = size();
  int low = temp -(temp - 1);
  T[] a = (T[]) new Object[temp];
  reset(INORDER);
  for (int i =0;i<temp; i++)
 {
     a[i]= getNext(INORDER);

     root = null;
     insertRec( a, 0 ,temp-1);
     add((T) a [i]);
  }
}

I don't have any issues with the rest of the code, but thought it would be helpful to see the whole method. This is part of a much larger class that manipulates Binary search trees, this method is supposed to balance the tree.

6
  • 3
    I believe the line int low = temp - (temp - 1) can be rewritten as int low = 1. Also, there doesn't seem to be enough information given here- which line is giving the error? Commented Nov 22, 2013 at 1:50
  • 1
    It might be useful to show exactly how you did it. Commented Nov 22, 2013 at 1:53
  • what is the size()? is any method that you create? Commented Nov 22, 2013 at 1:54
  • 2
    You can't cast an object into comparable like this. For a detailed answer, take a look at this SO question. Commented Nov 22, 2013 at 2:02
  • 1
    This code will also fail at runtime with the same error: Integer[] nums = (Integer[]) new Object[10];, which is perhaps a simpler example without generics. The answer given by Chthonic Project should give a usable way to accomplish what you want to do. Commented Nov 22, 2013 at 2:05

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.