In this post, I’m going to talk about some actual examples on how we can use Java generics to make our own code type safe.
In my last article, I explained how generics provide type safety in our code. More specifically, I explained how using code that has been implemented by other people using generics can give us the benefits of type safety.
In this post, I’m going to talk about how we can utilize generics in our own code (not someone else’s code) to achieve type safety and to brag to your friends how esoteric your code is (just kidding, I do not advocate unreadable code, it’s a pain for people reading your code).
And as always, I love examples that explain the motivation. I think it makes much more sense.
Disclaimer: You might have seen these examples somewhere on the Internet. If you find another article that explains these concepts, I would like to give the author credit for that.
Example 1: DRY Principle when Initializing a Generic Class
I just love this pattern. Google’s Guava library provides the
object to do precisely this.
So you’re just happily declaring lists in Java SE 6 as follows.
1 2 3
Don’t you wish you could just not repeat yourself typing the same type parameter on the right hand side of the expression? I guess Java SE 7 helps alleviate this issue a little bit by incorporating the diamond operator.
1 2 3
Hmm, slightly better. But we can do even better using Google Guava’s
1 2 3 4 5 6 7 8 9
“Wait, what? What is this magic? What just happened?”