Page 1 of 1

Generics

Posted: Thu Dec 21, 2017 6:40 am
by horst1a
could someone please help me with the following code ?

Code: Select all

public class Gen<G> {
	G g;
	Gen(G g)
	{
		this.g = g;
	}

public static void main(String[] args){
	Gen<String> arr[] = new Gen[5];
	arr[0]= new Gen("Java");
	arr[1]= new Gen(1);
	arr[2]= (Gen<String>) new Gen(1);
	
	System.out.println(arr[0]);
	System.out.println(arr[1]);
	System.out.println(arr[2]);
	}
	

}
Why does the arr , which is typed to String, accept objects ?

Re: Generics

Posted: Thu Dec 21, 2017 11:22 am
by admin
Multiple things -
1. arr is not typed to String. arr is of type Gen, which, in turn, is typed to String.
2. arrays are "reified", they don't care about generics at all. As far as arr is concerned, it is an array of Gen and not of Gen<String>. Try this: https://stackoverflow.com/questions/165 ... ed-in-java

Also, when you compiled it, it must have given a warning message about unsafe operations. It means the compiler is not able to guarantee that there will be no ClassCastException while using the elements of the array.