0

I have tried the following methods:

Optional[] arr1 = new Optional[0]; // Warning: Raw use of parameterized class 'Optional'

Optional<Integer>[] arr2 = new Optional[0]; // Warning: Unchecked assignment: 'java.util.Optional[]' to 'java.util.Optional<java.lang.Integer>[]'

Optional<Integer>[] arr3 = new Optional<Integer>[0]; // Error: Generic array creation

What is the problem with each different initialization above?

What would be the correct initialization method, enabling type resolution and safety in future access to the array?

Java 8

Snackoverflow
  • 2,219
  • 3
  • 24
  • 50
  • 1
    You can't create an array of a generic type because of [how generics work](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html) – Lino Aug 12 '20 at 13:52
  • I think you'll appreciate: [*Optional - The Mother of all Bikesheds*](https://inside.java/2017/04/11/optional/). – deduper Aug 12 '20 at 21:14
  • Whoever closed this question, should take another look. I am not creating an "array of generic type" like `T[]`. I am creating an array of a certain *known* type, which has a generic parameter. – Snackoverflow Aug 13 '20 at 11:34

0 Answers0