Java Tip: How those generics really work

Ever wonder how myList<Thingamajig> really works such that you don’t have to explicitly cast your reference when you do something like Thingamajig t = myList.get(0)? I mean, there isn’t any special ArrayList method that knows it’s just Thingamajigs, after all. Turns out, the compiler does the cast for you.

Including the <Thingamajig> when you create your list tells the compiler that only objects of type Thingamajig can go in the list. And since the compiler stops you from putting any other object in the list, it also knows it’s safe to cast any object that comes out of that list to a Thingamajig reference.
Here’s why this is a Good Thing. Casts can fail at runtime. It’s much better for the compiler to catch the problem.


About buffalobillion

Web Developer, JavaScript Balrog, Java dude, Ruby/Rails enthusiast. Guitar Playa.
This entry was posted in Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s