Creating a shared array in Java

Class A has a generic type, and in class B I want to create an array of type A objects with Integer as a generic parameter.

class A<T> {} class B { A<Integer>[] arr=new A[4]; //statement-1 B() { for(int i=0;i<arr.length;i++) arr[i]=new A<Integer>(); } } 

But in instruction-1, I get a warning for an unverified conversion. What is the correct way to create this array, so I do not need to use the suppress warning statement .

+4
source share
2 answers

Sometimes Java generics simply do not allow you to do what you want, and you need to effectively tell the compiler that what you do will be legal at runtime.
So, SuppressWarning annotation is used to suppress compiler warnings for the annotated element. Specifically, the unchecked category allows suppression of compiler warnings generated as a result of unchecked type casts. SuppressWarning annotation is used to suppress compiler warnings for the annotated element. Specifically, the unchecked category allows suppression of compiler warnings generated as a result of unchecked type casts. Check this..

 @SuppressWarnings("unchecked") A<Integer>[] arr = new A[3]; B(){ for(int i=0;i<arr.length;i++) arr[i]=new A<Integer>(); } 
+1
source
 @SuppressWarnings("unchecked") A<Integer>[] arr = new A[3]; B(){ for(int i=0;i<arr.length;i++) arr[i]=new A<Integer>(); } 
+1
source

Source: https://habr.com/ru/post/1400939/


All Articles