Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Java generics mainly a way of forcing static type on elements of a collection?

Tags:

java

generics

private ArrayList<String> colors = new ArrayList<String>();

Looking at the example above, it seems the main point of generics is to enforce type on a collection. So, instead of having an array of "Objects", which need to be cast to a String at the programmer's discretion, I enforce the type "String" on the collection in the ArrayList. This is new to me but I just want to check that I'm understanding it correctly. Is this interpretation correct?

like image 547
Harry Quince Avatar asked Apr 19 '09 23:04

Harry Quince


2 Answers

That's by far not the only use of generics, but it's definitely the most visible one.

Generics can be (and are) used in many different places to ensure static type safety, not just with collections.

I'd just like to mention that, because you'll come accross places where generics could be useful, but if you're stuck with the generics/collections association, then you might overlook that fact.

like image 130
Joachim Sauer Avatar answered Nov 14 '22 23:11

Joachim Sauer


Yes, your understanding is correct. The collection is strongly-typed to whatever type is specified, which has various advantages - including no more run-time casting.

like image 39
GalacticCowboy Avatar answered Nov 14 '22 22:11

GalacticCowboy