Home > Java > Using static Factory-methods to create Generics

Using static Factory-methods to create Generics

October 7th, 2009
Today I browsed through Project Coin and had a closer look at the language changes that made it into Java 7. Especially the proposal named ‘Improved Type Inference for Generic Instance Creation’ attracted my attention, because I already discovered a technique in Joshua Bloch’s great book Effective Java (2nd Edition) that helped me to reduce the effort to create Generics.
All you need is a Factory-class with static methods:

 Java |  copy code |? 
1
2
package com.java_blog.generics;
3
import java.util.HashMap;
4
 
5
public class GenericsFactory {
6
	public static <K, V> HashMap<K, V> newHashMap() {
7
		return new HashMap<K, V>();
8
	}
9
}


If you import these methods statically into your code, Generics-creation becomes very handy:


 Java |  copy code |? 
01
package com.java_blog.generics;
02
 
03
import java.util.HashMap;
04
import static com.java_blog.generics.GenericsFactory.newHashMap;
05
 
06
public class GenericsTest {
07
	public static void main(String[] args) {
08
 
09
		// old style
10
		HashMap<String, Integer> oldMap = new HashMap<String, Integer>();
11
 
12
		// new style
13
		HashMap<String, Integer> newMap = newHashMap();
14
	}
15
}


Happy Coding,
Tino


Share/Save/Bookmark

tino Java ,

  1. October 8th, 2009 at 11:56 | #1
    Just use google collections.
  2. Raja
    October 8th, 2009 at 15:29 | #2
    Or, we could also use google collections for this.
  3. October 14th, 2009 at 11:57 | #3
    Yes guys, you’re absolutely correct: you could use Google Collections for generic Maps, Lists, …

    But you can also apply this technique on self-created-Generics that are not available in Google Collections like e.g. MyGeneric<T1,T2,T3>.

    Tino.
  1. No trackbacks yet.
Security Code: