It is surprising to see that there are still many people who do not use generics even when they are using JDK 5 or higher. I can often see it especially when I teach some Java programming subjects at uni. Generics can be very useful and I use it a lot in my libraries and projects. So I'd like to talk about generics but not a basic knowledge of it. I will talk about Java generics in real life programming and how it can be useful as well as some unusual cases may occur and annoy you. I am also going to explain some common cases of generics usage in my next post that I have plan to write soon (hopefully). Then I'm going to write about more complex cases in the sense that it's complex when it's designed but rather simple when it's used, and it's also more practical. It means I'll probably write two more posts about generics so stay tuned if you're interested.
Before I start to talk about usefulness of it, let's start with problems that can happen if you don't use generics when using generified types. If your code looks like this, you're making your code error-prone.
List list = new ArrayList();
As it discards all the generic type information in the class. To see what exactly happens, better take a look at some example.
If you have type like
public class SomeType<T> {
public <E> void test(final Collection<E> collection) {
for (final E object : collection) {
System.out.println("E: " + object);
}
}
public void test(final Set<T> set) {
for (final T t : set) {
System.out.println("T from set: " + t);
}
}
public void test(final List<Integer> integerList) {
int result = 0;
for (final Integer integer : integerList) {
result += integer.intValue();
}
System.out.println("result: " + result);
}
}
and execute code like
final SomeType someType = new SomeType();
final List<String> list = Arrays.asList("some", "test", "value");
someType.test(list);
Then you will get ClassCastException
saying "java.lang.String cannot be cast to java.lang.Integer
" in runtime but no errors in compile-time. Why? because it uses public void test(final List<Integer> integerList)
method instead of public <E> void test(final Collection<E> collection)
. But why does it use the one taking List
of Integer
instead of the one with the Collection
of some type E
when the passed parameter is a List
of String
which is a Collection
of some type E
, in this case, String
? The reason is that SomeType
is generified but when using it, no generics are used. If generified type is used without generic type info specified, the Java compiler makes it like the old type in JDK prior to 5.0 which doesn't have generics.
Thus, the methods above all become like
public void test(final Collection collection)
public void test(final Set set)
public void test(final List integerList)
So the closest type matched with a List of String is a List
and that's why public void test(final List<Integer> integerList)
is called. But the method, public <E> void test(final Collection<E> collection)
, has nothing to do with the generic type specified in the class SomeType<T>
. It's just a generic method and the E
has nothing to do with the T
. Yeah, but if the type is generified, yet no generic type is specified when it is used, all the generics info including the ones in the generic methods is gone.
To solve the problem, you just need to specify the generic type. In the case above, you can even use just '?
' (wildcard) since you're not using the generic type specified in the class but the generic method, public <E> void test(final Collection<E> collection)
.
final SomeType<?> someType = new SomeType<Object>();
final List<String> list = Arrays.asList("some", "test", "value");
someType.test(list);
Now, with generics, you don't have the problem you had before without generics.
So, it's clear why you should use generics when using generified types. What I just explained is actually not new but well known to most Java programmers. Now, let's talk about some benefits from using generics.
You can avoid a problem that you have with arrays if you use generics. Arrays of reference types in Java are covariant so you may have a problem like this.
final Integer[] integerArray = { 1, 2, 3, 4, 5 };
final Object[] objectArray = integerArray;
objectArray[0] = "test";
There is no compile-time error, yet running this code results in java.lang.ArrayStoreException: java.lang.String
when objectArray[0] = "test";
is executed.
Unlike arrays, generics are invariant, so if you use generics like,
final List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
final List<Object> objectList = integerList;
You get a compile-time error.
final List<Object> objectList = (List<Integer>) integerList; // compile-time error
Even this one causes the compile-time error too since a List
of Integer
is not a subtype of List
of Object
(In arrays, an Integer
array is a subtype of Object
array).
On the other hand, you may need to cast it although it happens very occasionally. Here is an example taken from one of my libraries. In KommonLee ASM, there is a visitor class, MethodAnalysisClassVisitor
.
public class MethodAnalysisClassVisitor<T, M extends Member>
extends EmptyVisitor {
private final MemberCollector<M> memberCollector;
private final Class<T> theClass;
private final Map<M, String[]> memberToParameterNamesMap;
public MethodAnalysisClassVisitor(
final MemberCollector<M> memberCollector
, final Class<T> theClass
, final Map<M, String[]> memberToParameterNamesMap
) {
this.memberCollector = memberCollector;
this.theClass = theClass;
this.memberToParameterNamesMap = memberToParameterNamesMap;
}
// Remainder omitted...
}
This visitor collects all the methods / constructors and their parameter names. Why do I need this kind of tool? It's because I needed to get the parameter names of constructors in a class for one of my libraries, JSON Statham, but there was no easy way to get the parameter names of methods or constructors in Java. Reflection in Java certainly doesn't have this convenience which is, I believe, an integral part for library / framework development although it would be depending on what sort of library it is. So I had to use ASM to get the method parameter names. I was shocked when I first discovered it. Anyway, back to the original topic again, the visitor is used by AsmMethodAndConstructorAnalyser.
public class AsmMethodAndConstructorAnalyser
implements MethodAndConstructorAnalyser {
// ...
@Override
public <T> Map<Constructor<T>, String[]> findConstructorsWithParameterNames(
final Class<T> theClass
) throws IllegalArgumentException {
final Map<Constructor<T>, String[]> constructorToParameterNamesMap =
new LinkedHashMap<Constructor<T>, String[]>();
@SuppressWarnings({ "cast", "unchecked", "rawtypes" })
final Map<Constructor<?>, String[]> map =
(Map<Constructor<?>, String[]>) ((Map) constructorToParameterNamesMap);
getClassReader(theClass).accept(
new MethodAnalysisClassVisitor<T, Constructor<?>>(
constructorCollector, theClass, map
)
, 0
);
return constructorToParameterNamesMap;
}
// ...
}
I know that the type M
defined in the MethodAnalysisClassVisitor
is Constructor<T>
in this particular method as I'm passing Class<T>
and want to collect all the constructors in it which are all Constructor<T>
, yet the Java compiler can't figure it out so I get a compile-time error if I just do
final Map<Constructor<T>, String[]> constructorToParameterNamesMap =
new LinkedHashMap<Constructor<T>, String[]>();
getClassReader(theClass).accept(
new MethodAnalysisClassVisitor<T, Constructor<?>>(
constructorCollector, theClass, constructorToParameterNamesMap
)
, 0
);
Therefore, what I did was:
first, cast Map<Constructor<T>, String[]> constructorToParameterNamesMap
to a raw type Map then it will lose all the generic type info. second, I can cast it to Map
of any key value pair since the Java compiler erases all the generic types when it's compiled. finally, I ended up having the following lines of code. I had to add @SuppressWarnings({ "cast", "unchecked", "rawtypes" })
to make the compiler happy. I could do it because I know the constructors stored in the Map are all Constructors of T
type.
@SuppressWarnings({ "cast", "unchecked", "rawtypes" })
final Map<Constructor<?>, String[]> map =
(Map<Constructor<?>, String[]>) ((Map) constructorToParameterNamesMap);
getClassReader(theClass).accept(
new MethodAnalysisClassVisitor<T, Constructor<?>>(
constructorCollector, theClass, map
)
, 0
);
This doesn't happen often though. So most of the time, you don't need to do it and can enjoy type safety that generics offer.
Along with the benefit I mentioned above with the case compared with arrays, generics offer convenience of postponing specifying the type information until it is used with compile-time type safety. One example that everyone knows is Java's collections framework. The programmer of collections didn't know what types would be stored in the collections when it was created, thus when it came out, it stored just an object type as there were no generics. This is the part where Java loses static typing although it's a static type language. However, after introduction of generics, the users of collections can have compile-time type safety. Ironically, the collections are one of the most popular examples of how generics can be useful, yet according to Neal Gafter, it's one of the most important reasons why generics are implemented using type erasure and wild-card, which make generics more complex. If you're interested in it, you'd better watch his presentation.
Although Generics were introduced in JDK 5.0, the GJ compiler that can handle generics were introduced much earlier in JDK 1.3 but it was disabled according to the Java language specification.
Generics give us compile-time type safety but it's compile-time only because, as I just mentioned, it does type erasure which means the compiler removes all the generic type information when it compiles, and that's why we can't create a generic type object or array like.
T t = new T();
T[] t = new T[10];
This is impossible in Java and that's why you don't see method like E[] toArray()
but Object[] toArray()
and <T> T[] toArray(T[] a)
in the Collection class and its sub classes. You can create an array of E type if an instance of array of E is given as a parameter value. For example,
public <E> E[] copyArray(final E[] array) {
@SuppressWarnings("unchecked")
final E[] copiedArray = (E[]) Array
.newInstance(array
.getClass()
.getComponentType(),
array.length);
System.arraycopy(array, 0, copiedArray, 0, array.length);
return copiedArray;
}
It takes an array of E object then creates a new array object of E then copies all the elements in the given one to the new one then returns it.
How is it possible? It's possible because now I'm dealing with an 'array object' of E
type not the generic type E
directly so I can get the class of the array object in order to take the component type of the element stored in the array. So first, get the class of E[]
'object' (not class) which is a parameter value and given in runtime, then I can get the component type of it. However, the following case is impossible.
public <E, NE, F extends Function1<E, NE>> NE[] apply(
final F function, final E[] source
) {
final List<NE> list = new ArrayList<NE>();
for (final E element : source) {
list.add(function.apply(element));
}
@SuppressWarnings("unchecked")
final NE[] resultArray = list.toArray(
(NE[]) Array.newInstance(
NE[].class // <- compile time error here:
// Illegal class literal for the type parameter NE!!!
.getComponentType()
, list.size()
)
);
return resultArray;
}
Because there is no such thing as an NE[]
'class' (not object), there is no way to get the class. When it's compiled, NE[]
becomes an Object array (Object[]
).
I used to hate this type erasure as I had some issues when I developed my libraries. However, I do not anymore. It's not just because of the reason mentioned here. I have mine and will explain it later in this post.
So let me talk about why we use generics again. We use it to have compile-time type safety without having to decide the type when designing the API. One example can be found in my old post about Easier and Better Way to Use JDBC. Simply, it makes use of callback function object much more useful.
Let's say you want to map a type stored in a List
to some other type. If you don't use generics, you probably need to make a method for each mapped type like
public List<BigDecimal> takePricesOf(List<Product> list) {
List<BigDecimal> newList = new ArrayList<BigDecimal>();
for (Product product : list) {
newList.add(product.getPrice());
}
return newList;
}
public List<DiscountedProduct> toDiscountedProducts(
int discountRate, List<Product> list
) {
List<DiscountedProduct> newList = new ArrayList<DiscountedProduct>();
for (Product product : list) {
newList.add(new DiscountedProduct(product, discountRate));
}
return newList;
}
// and more...
(OK, here are actually generics used but it's only for using List
).
It can become one reusable method with some callback function object like.
public interface Mapper {
Object map(Object input);
}
public List<Object> mapWithoutGenerics(
// this mapperWithoutGenerics cannot be List<Object>
// since you want to pass a List of any type not just List<Object>.
Mapper mapperWithoutGenerics, List<?> list
) {
List<Object> newList = new ArrayList<Object>();
for (Object object : list) {
newList.add(mapperWithoutGenerics.map(object));
}
return newList;
}
When you use it.
List<Object> productPriceList = mapWithoutGenerics(new Mapper() {
public Object map(Object input) {
Product product = (Product) input;
return product.getPrice();
}
}, productList);
Now, you don't have compile-time type safety anymore so you may pass a List
of any type. So the following code doesn't cause any compile-time error but the runtime exception that is java.lang.ClassCastException
.
List<Object> productPriceList = mapWithoutGenerics(new Mapper() {
public Object map(Object input) {
Product product = (Product) input;
return product.getPrice();
}
}, Arrays.asList("Some", "String", "List"));
It can surely become much better with generics.
public interface Function1<T, R> {
R apply(T input);
}
public <T, R, F extends Function1<T, R>> List<R> map(F mapper, List<T> list) {
final List<R> newList = new ArrayList<R>();
for (final T t : list) {
newList.add(mapper.apply(t));
}
return newList;
}
Then when you use it.
final List<BigDecimal> productPriceList =
map(
new Function1<Product, BigDecimal>() {
@Override
public BigDecimal apply(final Product product) {
return product.getPrice();
}
}
, productList
);
Or the function object can be reused.
private static final Function1<Product, BigDecimal> PRODUCT_TO_PRICE_MAPPER =
new Function1<Product, BigDecimal>() {
@Override
public BigDecimal apply(final Product product) {
return product.getPrice();
}
};
//...
final List<BigDecimal> productPriceList =
map(PRODUCT_TO_PRICE_MAPPER, productList);
final List<BigDecimal> anotherProductPriceList =
map(PRODUCT_TO_PRICE_MAPPER, anotherProductList);
The other method that is toDiscountedProducts()
can be done with this generic map method and closure.
final int discountRate = 15;
final List<DiscountedProduct> discountedProductList =
map(
new Function1<Product, DiscountedProduct>() {
@Override
public DiscountedProduct apply(final Product product) {
return new DiscountedProduct(product, discountRate);
}
}
, productList
);
Although Java doesn't really have closure, the Function1 above is used as a closure because it's accessing a non-local variable, and in almost all the cases when people say that Java doesn't have closure, they actually mean a way to support first-class functions (e.g. lambda expression to support first-class functions in Java).
Speaking of generics used for collections, I should point out that it would have been much more useful, if the collections had got methods like select (or filter), map, etc.
So if you had got a List of Integer and wanted to get all the positive ones, you would have done like.
List<Integer> positiveIntegerList =
integerList.select(new Condition1<Integer>() {
public boolean isMet(Integer integer) {
return 0 < integer.intValue();
}
});
Or getting all the prices from the List of Product object as I already showed. Unfortunately Java's Collections don't have those methods. Well, my collection library has it, but it's incomplete and not so compatible with existing code using Java's collections although it has a way to convert from and to Java ones. So to keep using Java's collections, I made some helper methods to achieve the goal which is having one generic method to apply different kinds of functions to all the elements in the collections. By the way, why do I bother about it? Can't I just use for
or foreach
loop? Sure, I can. So why? With the generic methods mentioned above and function objects, I can focus on the actual problems. For instance, to get all the prices from the list of Product, my concern should be getting the price of each Product not how to use for
or foreach
loop.
Here, I need to worry about using foreach and creating ArrayList
.
List<BigDecimal> productPriceList = new ArrayList<BigDecimal>();
for (Product product : productList) {
productPriceList.add(product.getPrice());
}
With the generic one (if there were one), I wouldn't.
List<BigDecimal> productPriceList =
productList.map(new Function1<Product, BigDecimal>() {
public BigDecimal apply(Product product) {
return product.getPrice(); // <- here I'm focusing on getting the price.
}
});
Since Java doesn't support first-class function, the syntax is not so pleasant. However, JDK 8 will have lambda expression to support it so when it comes out, it can probably be like.
List<BigDecimal> productPriceList = productList.map(
(product) -> product.getPrice()
);
// It hasn't been finalised yet so the syntax can be different.
Anyway, Java collections still don't have those methods so, as I said already, I made the ones for the collections. So let me talk about one of these that is Selector
. What Selector
does is checking all the elements in a collection and takes only the ones that meet the given Condition
. I wanted to have only one Selector that can easily deal with all the classes extends Collection
instead of having one for each (e.g. ListToArrayListSelector
, ListToHashSetSetSelector
, SetToListSelector
, and so on). Thus I made it like this.
public class IterableToCollectionSelector<
E
, T extends Iterable<? extends E>
, C extends Condition1<? super E>
, R extends Collection<E>
> implements Selector1<T, C, R> {
@Override
public R select(final C condition, final T source) {
final R result = // <- How can I get the Collection instance of R?
for (final E element : source) {
if (condition.isMet(element)) {
result.add(element);
}
}
return result;
}
}
Here are Condition1 and Selector1 in my library.
public interface Condition1<T> {
boolean isMet(T input);
}
public interface Selector1<T, C, R> {
R select(C condition, T source);
}
Let me explain it step by step. First,
public class IterableToCollectionSelector<
E
, T extends Iterable<? extends E>
, C extends Condition1<? super E>
, R extends Collection<E>
> implements Selector1<T, C, R>
E
: E
is a type of an element stored in the given collection.
T
: T
is any type extends Iterable of the type extends E.
Why is it
Iterable
of any type extendsE
(? extneds E
)? Otherwise, you can't use aList
of any sub type ofE
. It would be easier to understand with an example. Let's say you need to get a List of Product the price of which is greater than 50 dollars. If it's justIterable<E>
then you have no problem with passing a List of Product yet you do have when you try to pass aList
ofDiscountedProduct
which is a sub class ofProduct
and it should be perfectly valid to pass it as a parameter of the selector made for Product (Think about Liskov substitution principle). If you haveIterable<? extends E>
, you can passE
type and any sub-types ofE
, in this case,Product
andDiscountedProduct
are all fine.Then why
T extends Iterable
? Can I just haveIterable
for the input type then I can remove the generic typeT
? Yes, it's OK, but what if there is anyone who wants to extends this class and wants to restrict the input type to only List instead of any sub-type of Iterable (probably if you care about Open/closed principle)? If you have a class like this.// Notice that T extends Iterable<? extends E> is gone,
// and it has Iterable<? extends E> instead (No T).
public class IterableToCollectionSelector<
E
, C extends Condition1<? super E>
, R extends Collection<E>
> implements Selector1<Iterable<? extends E>, C, R> {
}You can't restrict the input type to something other than
Iterable<? extends E>
, and if you try to override the select method in the sub-class of it.e.g.)
public class IterableToArrayListSelector<E> extends
IterableToCollectionSelector<E, Condition1<? super E>, ArrayList<E>> {
@Override
public ArrayList<E> select(
final Condition1<? super E> condition, final List<? extends E> source
) {
return super.select(condition, source);
}
}You will get a compile-time error because
T
is not the same as "? extends T
". In this case, "Iterable<? extends E>
" specified as a generic typeT
for theSelector1<T, C, R>
is not the same as "? extends T
" that is, in here,List<? extends E>
(one of "T extends Iterable<? extends E>
") in the overridden methodselect()
(It's not actually overridden asList<? extends E>
can't be a substitute forIterable<? extends E>
here). Still not sure whyList
can't be used? Well, think about this.List<String>
is not the same as and can't be a substitute forList<Object>
. You know it, and I already explained it earlier when I talked about the side-effect of using arrays. Then think about this one. CanList<List<?>>
be a substitute forList<Iterable<?>>
? No, it's just likeList<String>
andList<Object>
, and the problem we have here is the same.So
public class IterableToCollectionSelector<
E
, T extends Iterable<? extends E>
, C extends Condition1<? super E>
, R extends Collection<E>
> implements Selector1<T, C, R>gives me freedom to restrict the input iterable to whatever extends Iterable I want.
e.g.)
public class IterableToArrayListSelector<E>
extends IterableToCollectionSelector<
E
, List<? extends E>
, Condition1<? super E>
, ArrayList<E>
>There will be a compile-time error when passing a Set instead of a List for the input value of the select() method.
C extends Condition1<? super E>
:
Next one is C extends Condition1<? super E>
. What? Why is the input type of the Condition1
"? super E
"? Because, with "? super E
", I can have one Condition1
object for many sub-types of the type E
. Imagine that you want to get a List
of Product
the price of which is greater than 20, you can have a Condition1
for Product
, then if you also need to get a List
of DiscountedProduct
the price of which is also greater than 20, you can reuse that Condition1
object for it as DiscountedProduct
is a sub-type of Product
which means Condition1<Product>
is a kind of Condition1<? super DiscountedProduct>
. If I have "C extends Condition1<E>
" then I can't do that, but because it's "C extends Condition1<? super E>
", I can.
R
: The last one is R
. R extends Collection<E>
so it can be any sub-type of Collection.
Now let's look at the method. Here I have some problem.
public R select(final C condition, final T source) {
final R result = // <- How can I get the Collection instance of R???
for (final E element : source) {
if (condition.isMet(element)) {
result.add(element);
}
}
return result;
}
If it's one type of Collection
, I can easily create it but it's not determined yet. It will be set when it's used. Then why don't I postpone instantiation of it until it's used. More precisely when the selector is instantiated. So I just create another type to create one of Collection
also using generics.
public interface CollectionCreator<E, T extends Collection<? extends E>> {
T createCollection();
}
So it can be used to create any sub-types of Collection.
e.g.) for ArrayList
public class ArrayListCreator<E> implements CollectionCreator<E, ArrayList<E>> {
@Override
public ArrayList<E> createCollection() {
return new ArrayList<E>();
}
}
for HashSet
public class HashSetCreator<E> implements CollectionCreator<E, HashSet<E>> {
@Override
public HashSet<E> createCollection() {
return new HashSet<E>();
}
}
With all these, the final version of IterableToCollectionSelector
is
public class IterableToCollectionSelector<
E
, T extends Iterable<? extends E>
, C extends Condition1<? super E>
, R extends Collection<E>
> implements Selector1<T, C, R> {
private final CollectionCreator<E, ? extends R> collectionCreator;
public <CC extends CollectionCreator<E, ? extends R>>
IterableToCollectionSelector(
final CC collectionCreator
) {
this.collectionCreator = collectionCreator;
}
@Override
public R select(final C condition, final T source) {
final R result = collectionCreator.createCollection();
for (final E element : source) {
if (condition.isMet(element)) {
result.add(element);
}
}
return result;
}
}
It needs to have CollectionCreator
but it's immutable so I don't need to worry about the state of the selector object once it's created.
When IterableToCollectionSelector
is used, it looks
// selector for the List of Product.
final IterableToCollectionSelector<
Product, Iterable<Product>, Condition1<Product>, ArrayList<Product>
> collectionSelector =
new IterableToCollectionSelector<
Product, Iterable<Product>, Condition1<Product>, ArrayList<Product>
>(new ArrayListCreator());
final List<Product> resultList =
collectionSelector.select(greaterThan20, productList);
// selector for the List of DiscountedProduct
final IterableToCollectionSelector<
DiscountedProduct
, Iterable<DiscountedProduct>
, Condition1<Product>
, ArrayList<DiscountedProduct>
> collectionSelector2 =
new IterableToCollectionSelector<
DiscountedProduct
, Iterable<DiscountedProduct>
, Condition1<Product>
, ArrayList<DiscountedProduct>
>(new ArrayListCreator());
final List<DiscountedProduct> resultList2 =
collectionSelector2.select(greaterThan20, discountedProductList)
Wait, do I have to create the IterableToCollectionSelector
whenever I need to use it for a different type? It seems like it's waste of memory and not to mention of boilerplate code. OK, here comes why I don't hate generics' type erasure anymore. Considering type erasure, both objects, used above, actually have no difference in runtime.
So what I can do is that I can create a helper class containing one really generic IterableToCollectionSelector
then cast it using a generic method so that it always returns the same instance but can be used for different types with compile-time type safety. It would be clear if I just show the code.
public class CollectionUtil {
private static final IterableToCollectionSelector<
?
, ? extends Iterable<?>
, ? extends Condition1<?>
, ? extends ArrayList<?>
> ITERABLE_TO_ARRAY_LIST_SELECTOR =
new IterableToCollectionSelector<
Object
, Iterable<?>
, Condition1<Object>
, ArrayList<Object>
>(new ArrayListCreator<Object>());
public static <
E
, T extends Iterable<? extends E>
, C extends Condition1<? super E>
> IterableToCollectionSelector getIterableToCollectionSelector() {
@SuppressWarnings("unchecked")
final IterableToCollectionSelector<E, T, C, ArrayList<E>>
iterableToCollectionSelector =
(IterableToCollectionSelector<E, T, C, ArrayList<E>>) ITERABLE_TO_ARRAY_LIST_SELECTOR;
return iterableToCollectionSelector;
}
}
And similarly, ArrayListCreator
doesn't have to be created more than once. It doesn't have any state so one instance can be and should be reused.
public class ArrayListCreator<E>
implements CollectionCreator<E, ArrayList<E>> {
public static final ArrayListCreator<Object> ARRAY_LIST_CREATOR =
new ArrayListCreator<Object>();
@Override
public ArrayList<E> createCollection() {
return newArrayList();
}
public static <E> ArrayListCreator<E> getInstance() {
@SuppressWarnings("unchecked")
final ArrayListCreator<E> arrayListCreator =
(ArrayListCreator<E>) ARRAY_LIST_CREATOR;
return arrayListCreator;
}
}
So CollectionUtil
is rewritten.
public class CollectionUtil {
private static final IterableToCollectionSelector<
?
, ? extends Iterable<?>
, ? extends Condition1<?>
, ? extends ArrayList<?>
> ITERABLE_TO_ARRAY_LIST_SELECTOR =
new IterableToCollectionSelector<
Object
, Iterable<?>
, Condition1<Object>
, ArrayList<Object>
>(ArrayListCreator.getInstance());
public static <
E
, T extends Iterable<? extends E>
, C extends Condition1<? super E>
> IterableToCollectionSelector getIterableToCollectionSelector() {
@SuppressWarnings("unchecked")
final IterableToCollectionSelector<E, T, C, ArrayList<E>> iterableToCollectionSelector =
(IterableToCollectionSelector<E, T, C, ArrayList<E>>) ITERABLE_TO_ARRAY_LIST_SELECTOR;
return iterableToCollectionSelector;
}
}
@SuppressWarnings("unchecked")
final IterableToCollectionSelector<E, T, C, ArrayList<E>> iterableToCollectionSelector =
(IterableToCollectionSelector<E, T, C, ArrayList<E>>) ITERABLE_TO_ARRAY_LIST_SELECTOR;
This is possible due to type erasure, so you don't have to create many objects of the same type with different generic type info (e.g. instances of the same type, 'IterableToCollectionSelector
', with 'different generic types' like different E
, T
, C
) which will be all the same in runtime. That's why I do not hate type erasure anymore. Of course, you need to @SuppressWarnings
to make the compiler quiet, but it's not a big deal and I know what I'm doing. It's perfectly valid.
The condition can be reused.
final Condition1<Product> greaterThan20 = new Condition1<Product>() {
private final BigDecimal twenty = new BigDecimal("20");
@Override
public boolean isMet(final Product input) {
return 0 > twenty.compareTo(input.getPrice());
}
};
Now I can just do,
final IterableToCollectionSelector<
Product
, Iterable<Product>
, Condition1<Product>
, ArrayList<Product>
> collectionSelectorForProduct =
CollectionUtil.getIterableToCollectionSelector();
final List<Product> resultForProduct =
collectionSelectorForProduct.select(greaterThan20, productList);
final IterableToCollectionSelector<
DiscountedProduct
, Iterable<DiscountedProduct>
, Condition1<Product>
, ArrayList<DiscountedProduct>
> collectionSelectorForDiscountedProduct =
CollectionUtil.getIterableToCollectionSelector();
final List<DiscountedProduct> resultForDiscountedProduct =
collectionSelectorForDiscountedProduct.select(greaterThan20, discountedProductList);
Each time when you get an instance of IterableToCollectionSelector
using the getIterableToCollectionSelector()
method, you get the same IterableToCollectionSelector
instance.
OK, that sounds good but do I really need to know all those complex E
, T
, C
, R
and even wildcard like "? extends E
" or "? super E
"? Well, you don't have to. It depends on what you do. If you're a library or framework developer, you should probably. Otherwise, not really. The library or API designer should carefully design it to offer APIs that are easy to use and understand for the users of the library. The designer or architect, on the other hand, should know the things I talked about here to make complex things simple. That's our job, isn't it? Making a complex thing simple then solve it. Anyway, most of the time, you don't need to deal with that kind of complex API if you're an application developer. Your company should have at least one person who can deal with it and he/she should provide easy to use APIs. If your company doesn't have any, ask your boss to hire one. 🙂 Using well designed good APIs can surely save your time which means saving your company's money. Also less error-prone.
So how can the IterableToCollectionSelector
be simple so that the users wouldn't need to care about E
, T
, C
, etc.
The library designer should create more specific type of selector like
public final class IterableToArrayListSelector<E>
extends IterableToCollectionSelector<
E
, Iterable<? extends E>
, Condition1<? super E>
, ArrayList<E>
> {
IterableToArrayListSelector(final ArrayListCreator<E> collectionCreator) {
super(collectionCreator);
}
}
Then CollectionUtil
becomes
public class CollectionUtil {
private static final IterableToArrayListSelector<?>
ITERABLE_TO_ARRAY_LIST_SELECTOR =
new IterableToArrayListSelector<Object>(ArrayListCreator.getInstance());
public static <E> IterableToArrayListSelector<E>
getIterableToArrayListSelector() {
@SuppressWarnings("unchecked")
final IterableToArrayListSelector<E> iterableToCollectionSelector =
(IterableToArrayListSelector<E>) ITERABLE_TO_ARRAY_LIST_SELECTOR;
return iterableToCollectionSelector;
}
}
Now using it is much easier.
(with static import)
import static your.package_name.here.CollectionUtil.*;
// ...
final IterableToArrayListSelector<Product> arrayListSelectorForProduct =
getIterableToArrayListSelector();
final List<Product> resultForProduct =
arrayListSelectorForProduct.select(greaterThan20, productList);
final IterableToArrayListSelector<DiscountedProduct>
arrayListSelectorForDiscountedProduct = getIterableToArrayListSelector();
final List<DiscountedProduct> resultForDiscountedProduct =
arrayListSelectorForDiscountedProduct.select(greaterThan20, discountedProductList);
You may not be satisfied yet, because you have the variables for the IterableToArrayListSelector
objects. Should you have these? No, you don't have to. So you probably try like this.
final List<Product> resultForProduct =
getIterableToArrayListSelector()
.select(greaterThan20, productList);
Yet, this doesn't work. When getIterableToArrayListSelector()
is called there is no generic type info given so it returns just an object of IterableToArrayListSelector<Object>
. Thus it causes a compile-time error on calling select(greaterThan20, productList)
.
It can be solved by specifying the generic type like.
final List<Product> resultForProduct2 =
CollectionUtil.<Product>getIterableToArrayListSelector()
.select(greaterThan20, productList);
It's not so elegant though. It can be solved as well. How? instead of having the getIterableToArrayListSelector()
method to get an instance of IterableToArrayListSelector
, why don't I just create another generic select()
method which does both getting the instance and calling the select()
method in it.
So CollectionUtil
is re-written.
public class CollectionUtil {
private static final IterableToArrayListSelector<?>
ITERABLE_TO_ARRAY_LIST_SELECTOR =
new IterableToArrayListSelector<Object>(ArrayListCreator.getInstance());
public static <
E
, T extends Iterable<? extends E>
, C extends Condition1<? super E>
> ArrayList<E> select(
final C condition, final T iterable) {
final IterableToArrayListSelector<E> iterableToCollectionSelector =
(IterableToArrayListSelector<E>) ITERABLE_TO_ARRAY_LIST_SELECTOR;
return iterableToCollectionSelector.select(condition, iterable);
}
}
How to use? Really simple. (also with static import)
import static your.package_name.here.CollectionUtil.*;
// ...
final List<Product> resultForProduct = select(greaterThan20, productList);
final List<DiscountedProduct> resultForDiscountedProduct =
select(greaterThan20, discountedProduct);
So it's
final IterableToCollectionSelector<
Product
, Iterable<Product>
, Condition1<Product>
, ArrayList<Product>
> collectionSelectorForProduct =
getIterableToCollectionSelector();
final List<Product> resultForProduct =
collectionSelectorForProduct.select(greaterThan20, productList);
VS
final List<Product> resultForProduct = select(greaterThan20, productList);
As you can see, depending on how you use generics it can give you a really nice, simple and easy to use API.
Just a moment. It might not be enough. That select takes an Iterable
object and returns an ArrayList
object, but what if I want to get HashSet
instead, or what about taking an array as an input parameter instead of an Iterable
object? It can be accomplished too, but I'm not going to explain it here. I'll do it later when I talk about good API design in another post not in the generics series.
In the meantime, you can use what I've already provided in my library that is KommonLee.
If you use it, you can simply do
final List<Product> anotherPositiveIntegerList = selector()
.fromIterable()
.toArrayList()
.select(greaterThan20, productList);
OR
final Set<Product> anotherPositiveIntegerList = selector()
.fromIterable()
.toHashSet()
.select(greaterThan20, productList);
OR
Product[] productArray = // ...
final List<Product> anotherPositiveIntegerList = selector()
.fromArray()
.toArrayList()
.select(greaterThan20, productArray);
and so on...
More examples are >>here<<
It also has Mappers and SelectableMappers so you can convert one type stored in a Collection to another.
Also the example code I used here is available on Github. Example Code: CLICK HERE!!!
Next post about generics would be about something easier than the selector example. So it would be some practical but easier, then the final post would be about really complex one when it's designed but easy when it's used. It is also very practical and useful. Unfortunately, however, I can't tell when I can write it as I need to think about good examples to explain. As you can see above, it can be difficult to understand without example code (or even with it, still difficult). I do actually have some examples but it's the code I made for my work so I can't just use it. Anyway, I will figure it out so stay tuned.
Java Generics: Generics in Real Life Programming - http://t.co/wLMJyLCP - @DZone Big Link by kevinshlee
— DZone (@DZoneInc) 7 December 2012
Thanks for those who retweeted and favorited this post.