[TUT] Easier / Quicker Generic Collection Creation

Sick of repeating your generics declaration?Sick of repeating your generics declaration?

[java]
List<SomeObject> listOfSomething = new ArrayList<SomeObject>();
Map<SomeKey, SomeObject> mapOfSomething = new HashMap<SomeKey, SomeObject>();
[/java]

For a quick and easy way to create a collection of objects you can do the below.

Create yourself a util class:

[java]
package com.blundell.util;

import java.util.ArrayList;
import java.util.HashMap;

public class Collections {

public static <E> ArrayList<E> newArrayList() {
return new ArrayList<E>();
}

public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}

}
[/java]

Then each time you only need to declare your generics once.

[java]
List<SomeObject> listOfSomething = Collections.newArrayList();
Map<SomeKey, SomeObject> mapOfSomething = Collections.newHashMap();
[/java]

This is due to Type Inference. Inspired by Joshua Bloch’s – Effective Java (second edition)

Enjoy.

Comments

One response to “[TUT] Easier / Quicker Generic Collection Creation”

  1. esta avatar
    esta

    good blog.tnx