Sunday, July 17, 2011

Generic Java Methods And Type Inference

To create test data in Java I often wrote things like this:
List<String> names = new ArrayList<String>();
names.add("Tick"); 
names.add("Trick");
names.add("Track");
...
Generic methods and type inference make this task a lot easier:
public static <T> List<T> newArrayList(T... entries) {
  return new ArrayList<T>(Arrays.asList(entries));
}
The following JUnit test shows how to use this code:
public class ListBuilderTest {

  @Test
  public void test() {
    List<String> l = ListBuilder.newArrayList("Tick", "Trick", "Track");
      assertThat(l.size(), equalTo(3));
      assertThat(l, hasItem("Tick"));
      assertThat(l, hasItem("Trick"));
      assertThat(l, hasItem("Track"));
    }
}

By the way: I love the JUnit 4 org.junit.matchers.JUnitMatchers.* and org.hamcrest.CoreMatchers.* Matchers :-)

Of course you do not have to implement this code yourself. You can for example use the great guava libraries.

No comments:

Post a Comment