OCP 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:

OCP Generics

Post by horst1a »

Hello , I ve read a lot about generics but still dont understand it.

Code: Select all

import java.util.*;
public class Book12{ 
	public static void main(String args[])
	{
                BookList<TextBook12> list = new BookList<>();
		list.add(new TextBook12());
		System.out.println(list.count); 
	}
} 

class TextBook12 extends Book12{ }

class BookList<TextBook12> extends ArrayList<TextBook12>
{ 
	public int count = 0;
}
I dont understand why i get the ClassCastException. Thought i typed the ArrayList to TextBook12.
However, I cannot insert anything, not even an object of type TextBook12.

Why and how can i resolve it.
Thanx in advance
Last edited by admin on Thu Nov 09, 2017 8:47 pm, edited 1 time in total.
Reason: Updated to put code within [code] and [/code]

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

Re: OCP Generics

Post by admin »

Did you read this? viewtopic.php?f=2&t=473
You will never get a ClassCastException due to generics because generics are a compile time thing and ClassCastException is a runtime thing. All generic information is removed by the compiler while generating the class files. So if you are getting a ClassCastException, then the problem is something else, not generics.


BTW, please use code tags while posting code. (I have updated your post)

Post Reply

Who is online

Users browsing this forum: Google [Bot] and 3 guests