Generic Type Inference and varargs to make code smaller
0 Comments Published March 12th, 2009 in Java Tags: .Recently at Devoxx I've heard that type inference will be available on Java7 to shorten collections instantiations. (If I remember correctly, from Josh Bloch's workshop).
I catched the idea, and started using Type Inference and Varargs to shorten my code.
Here's an example:
static <K, V> Map<K, V> newHashMap() {
return new HashMap<K, V>();
}
static <T> List<T> newArrayList(T... t) {
return new ArrayList<T>(Arrays.asList(t));
}
public static void main(String[] args) {
// if you think that this is too verbose:
Map<String, Object> map1 = new HashMap<String, Object>();
// try using the generics type inference:
Map<String, Object> map2 = newHashMap();
// Now, talking about lists...
// type inference and varargs can be used to shorten this code:
List<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
// into a single line:
List<Integer> list2 = newArrayList(1, 2, 3);
// the effects are the same:
System.out.println("maps are equal: " + map1.equals(map2));
System.out.println("lists are equal: " + list1.equals(list2));
}
Search
Calendar
| M | T | W | T | F | S | S |
|---|---|---|---|---|---|---|
| « Feb | Apr » | |||||
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 | 31 | |||||
Archives
Categories
Tag Cloud
Android API Bash Bios CSS Development Eclipse Encription Error Handling Font Git Google GWT Hardware How-To HTML Installation iPod Java JavaScript Karmic Linux Lucks MacBook Open Source Opinion OSX Pitfalls Pkg Practices Python Resume Security Software Suspend TDD Testing Tools Top Down Tricks Ubuntu Uninstall Wakup On Lan Web Workaround
WP Cumulus Flash tag cloud by Roy Tanck and Luke Morton requires Flash Player 9 or better.
Blog License
Blogs I like
Books on the desk
Friends' Blogs
- Antonio Terreno & Valter Bernardini
- Bruno Bossola
- Daniele Galluccio
- Domenico Ventura
- Ed Schepis
- Fabrizio Gianneschi
- Luca Grulla
- Luigi Zanderighi
- Marcello Teodori
- Mida Boghetich
- Muralidharan Chandrasekaran
- Piero Ricca
- Renzo Borgatti
- Simone Bordet
- Simone Bruno
- Uberto Barbini
- Valvolog
- Webtide blogs (Greg Wilkins & Jan Bartel)
Links





















No Responses to “Generic Type Inference and varargs to make code smaller”
Please Wait
Leave a Reply