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

Create thread in Java (two ways)

There are two ways you can create new Thread in Java. First one is to implement Runnable. This is more common way of doing this, but if you look at the Thread's code, you will see that Thread only calls run() on Runnable object, so you basically don't need it here. Second way is not to use Runnable, but instead just implement Thread's run() ant that's it!

Using Runnable:
  Thread secondMethod = new Thread(new Runnable() {
      int index = 0;
      @Override
      public void run() {
          try {
              while (index < 100) {
                  int interval = (int) ((Math.random() * 500) + 500);
                  Thread.sleep(interval);
                  System.out.print("*");
                  index++;
              }
          } catch (InterruptedException exc) {
              //Empty
          }
      }
  });
Without Runnable:
Thread firstMethod = new Thread() {
    int index = 0;
    @Override
    public void run() {
        try {
            while (index < 100) {
                int interval = (int) ((Math.random() * 500) + 500);
                sleep(interval);
                System.out.print(".");
                index++;
            }
        } catch (InterruptedException exc) {
            //Empty
        }
    }
};