Programmer's Blog: Get and Put Principle in Java Generics
It is hard to imagine modern Java development without using generics. While they look more simple and straightforward than C++ templates, it makes sense to invest some time to learn their best practices. In this post I want to talk about "Get and Put Principle" – one of the most important rules to remember when working with generics.
Basic Information
Quite often "Get and Put Principle" is defined in terms of getting values out of a data structure and putting values into it:
Use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don't use a wildcard when you both get and put.
Let's look at how judicious application of "Get and Put Principle" allows for creation of more flexible code. Assume you need to implement a method which gets the values from a source collection and adds them to a destination collection. It might look like this:
Read full article from Programmer's Blog: Get and Put Principle in Java Generics
No comments:
Post a Comment