Page 1 of 1

OCP Generics

Posted: Thu Nov 09, 2017 3:24 pm
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

Re: OCP Generics

Posted: Thu Nov 09, 2017 8:47 pm
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)