2

I already read some of the answers following which I know 1 of the technique of creating a generic array is using reflection but what of I write the below generic method for creating an array? Is this potentially dangerous in any way?

public <E> E[] getArray(int size, Class<E> e) { 

          E[] arr = (E[])new Object[size];    
          return arr;    

}
8
  • 1
    Looks wrong to me as you've actually created an array of Object not an array of E. Have a look at how to do it. Commented Jan 1, 2019 at 7:53
  • Yeah! I agree! But I want to know can it cause a runtime exception in any way? Commented Jan 1, 2019 at 7:57
  • what's the type input Class<E> e you're planning to use for ? Commented Jan 1, 2019 at 7:59
  • 1
    @AnkitSingodia Try it and see. I think if you actually try and assign an object of type E into an element of the array, you'll get an exception. Commented Jan 1, 2019 at 8:00
  • 1
    By the way, the Class<E> e is unused in your current code. If you remove it, your method invocation would look like : Integer[] strArr = myStack.getArray(10).. What's still an unsolved piece of this puzzle is what is myStack an instance of, does it imply any type bound to it? Commented Jan 1, 2019 at 8:13

2 Answers 2

3

It simply doesn't work.

The compiler will allow you to write:

String[] sarr = new YourClass().getArray(10,String.class);

but in runtime you'll get an exception:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

Sign up to request clarification or add additional context in comments.

3 Comments

Nope. I tested it for the case you mentioned. It runs just fine.
@AnkitSingodia that's very strange, since I also tested it. Which Java version are you using? (not that I think it should make a different, though) Can you post the exact code you tried?
My bad. That indeed produces a runtime exception.
0

Arrays and generics are concepts from two different eras of Java, which are not designed for being mixed. If you want typesafe genericity, why not use ArrayList instead of the array?

1 Comment

Yeah! Arraylist indeed does go well with generics, but just to get some concepts clear in my head - I was trying this :)

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.