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.

Dakuwan Locke
  • 67
  • 1
  • 5
  • 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? – SimonT Nov 22 '13 at 01:50
  • 1
    It might be useful to show exactly how you did it. – ChiefTwoPencils Nov 22 '13 at 01:53
  • what is the size()? is any method that you create? – João Silva Nov 22 '13 at 01:54
  • I added more in reaction to your comments. The real piece that I can't figure out is why my generic array isn't working even though my class extends Comparable. – Dakuwan Locke Nov 22 '13 at 02:01
  • 2
    You can't cast an object into comparable like this. For a detailed answer, take a look at [this SO question](http://stackoverflow.com/questions/1817524/generic-arrays-in-java). – Chthonic Project Nov 22 '13 at 02: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. – SimonT Nov 22 '13 at 02:05

0 Answers0