1

I have the following structure:

public class SomeObject<T> {

    int key;
    T value;
    ...
}

And in another class:

public class TestSomeObject<T> {

    SomeObject<T>[] data;

    TestSomeObject() {
         this.data =  (SomeObject<T>[]) new Object[capacity];
    }
}

Of course, that line in the constructor utterly fails with the Exception:

[Ljava.lang.Object; cannot be cast to [SomeObject;

Are there any workarounds for this? Or is there any way I could restructure it to make it work?

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
Alexandr
  • 708
  • 9
  • 29

3 Answers3

3

Use

@SuppressWarnings("unchecked")
TestSomeObject() {
     this.data =  new SomeObject[capacity];
}
wero
  • 32,544
  • 3
  • 59
  • 84
0

You cant't cast an new Object() to SomeObject.

Maybe you want something like this?

public class TestSomeObject<T> {

  SomeObject<T>[] data;

  TestSomeObject() {
       this.data =  new SomeObject[] {new SomeObject<T>()};
  }

  public static void main(String... args) {
    new TestSomeObject<String>();
  }

}
Benjamin Schüller
  • 2,104
  • 1
  • 17
  • 29
0

If Object in "new Object[capacity];" is java.lang.Object, it's normal. You can't cast a new Object into anything. You have to do:

this.data = new SomeObject<T>[capacity];
Asoub
  • 2,273
  • 1
  • 20
  • 33