Wednesday, March 12, 2014

Collection add elements in single line


Passing arrays instance arguments in single line of code is very useful. For example you can do something like this:
addNumbers(new int[] {1,2,3});
And it will work perfectly, but for collections you can't to that. However using anonymous inner classes with instance initialization we can get similar effect:
addNumbers(new ArrayList<Integer>(3) {{ add(1); add(2); add(3); }});
If we expand this code, it will be more clear how it works.
addNumbers(new ArrayList<Integer>(3) {//anonymous class
  //instance initialization block
  { 
    add(1); 
    add(2); 
    add(3); 
  }
});
Just for completeness here are addNumber methods:
private static int addNumbers(int[] numbers) {
    int result = 0;
    for (int number : numbers) {
        result += number;
    }
    return result;
}

private static Integer addNumbers(Collection<Integer> numbers) {
    Integer result = 0;
    for (Integer number : numbers) {
        result += number;
    }
    return result;
}

No comments:

Post a Comment