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;    

}
Ankit Singodia
  • 331
  • 3
  • 13
  • 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](https://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java). – dave Jan 01 '19 at 07:53
  • Yeah! I agree! But I want to know can it cause a runtime exception in any way? – Ankit Singodia Jan 01 '19 at 07:57
  • what's the type input `Class e` you're planning to use for ? – Naman Jan 01 '19 at 07: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. – dave Jan 01 '19 at 08:00
  • @nullpointer: I used that to have a compile time check. Because of Class param, the below statement gets an error at compile time: Integer[] strArr = myStack.getArray(10, String.class); And so the client is bound to retrieve the array in the appropriate data type i.e String in above case. – Ankit Singodia Jan 01 '19 at 08:04
  • *below statement gets an error at compile time*... which IMHO, is a better way in which compiler can help you with to prevent trying something like `Integer[] strArr = myStack.getArray(10, String.class);`, those types are not compatible to be casted. – Naman Jan 01 '19 at 08:06
  • 1
    By the way, the `Class 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? – Naman Jan 01 '19 at 08:13
  • If you have a `Class` object representing the element type, why not use `Array.newInstance(e, size)` instead of `new Object[size]`? – Holger Jan 07 '19 at 17:46

2 Answers2

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;

Eran
  • 359,724
  • 45
  • 626
  • 694
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?

Stephan Herrmann
  • 7,168
  • 1
  • 22
  • 33