Java initializer block trick

Here's a neat trick Kevlin Henney found in some code Michael Feathers posted at http://pastie.org/534364 Instead of doing this:
ArrayList<Integer> values = new ArrayList<Integer>();
values.add(1);
values.add(2);
values.add(3);
You can do this:
ArrayList<Integer> values = new ArrayList<Integer>() {{
    add(1);
    add(2);
    add(3);
}};

1 comment:

  1. Anonymous3:19 am

    This comment has been removed by a blog administrator.

    ReplyDelete