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?

3
  • 2
    What do you wish this to do : this.data = (SomeObject<T>[]) new Object[capacity];? Commented Aug 7, 2015 at 9:13
  • Using generics and casting... Why? Commented Aug 7, 2015 at 9:14
  • 1
    stackoverflow.com/questions/2434041/… Commented Aug 7, 2015 at 9:15

3 Answers 3

3

Use

@SuppressWarnings("unchecked")
TestSomeObject() {
     this.data =  new SomeObject[capacity];
}
Sign up to request clarification or add additional context in comments.

Comments

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

}

Comments

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];

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.