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));
}    

No Responses to “Generic Type Inference and varargs to make code smaller”  

  1. No Comments

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



Calendar

March 2009
M T W T F S S
« Feb   Apr »
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Follow me

twitter flickr LinkedIn feed

Subscribe by email

Enter your email address:

Archives


Categories

Tag Cloud


Listening