Generics

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
horst1a
Posts: 37
Joined: Mon Jun 12, 2017 2:16 am
Contact:

Generics

Post 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 ?

admin
Site Admin
Posts: 10398
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Generics

Post 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.

Post Reply

Who is online

Users browsing this forum: No registered users and 5 guests