After Generics, we don't need to typecast the object. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

After Generics, we don't need to typecast the object.

List<String> list = new ArrayList<String>(); list.add("hello"); String s = list.get(0); i saw it on JavaTpoint. But here..Without using Generics we can get the same result

8th Jan 2017, 2:24 PM
Somnath Ghosh
Somnath Ghosh - avatar
1 Answer
0
As you said, using generics avoids typecasts. typecasts are always bad as the compiler doesnt check if the cast is possible, so you get your error on runntime. ArrayList l=new ArrayList (); l.add ("hi"); l.add (new JPanel ()); String s=(String)l.get (1); This would cause a ClassCastExeption at runtime. By using generics you imidiatelly see if there is an error before you compile and you have an errorsource less. If you would use object all the time instead of <T> while coding libraries (like arraylists) your library wouldn't be able to be used easily and you and the users would always check if they put the right types in. It's really difficult to explain. In a nutshell it avoids using dangerous typecasts.
8th Jan 2017, 7:28 PM
No One
No One - avatar