Initializing and adding value in List and ArrayList in single line - double brace initialization



We can declare, initialize and add value in List and ArrayList in single line in following ways -
  1. Using Arrays.asList method >



1) Anonymous inner class / double brace initialization


Example - To declare, Initialize and add value in ArrayList in single line.
import java.util.ArrayList;
public class InitialzeArrayListInOneLine {
   public static void main(String[] args) {
          ArrayList<String> arrayList = new ArrayList<String>() {{
          add("a");
          add("b");
          add("c");
          }};
   }
}
Here we took just 1 line to declare, initialize ArrayList and add 3 values in it using Anonymous inner class.

Without Anonymous inner class / double brace initialization above code will be written in many lines >
import java.util.ArrayList;
public class InitialzeArrayListInOneLine {
   public static void main(String[] args) {
          ArrayList<String> list = new ArrayList<String>();
          list.add("a");
          list.add("b");
          list.add("c");
   }
}
Here we took 4 lines to declare, initialize array and add 3 values in it.


2) Using Arrays.asList method >



Example - To Initialize and add value in List in single line.
import java.util.Arrays;
import java.util.List;
public class InitialzeArrayListInOneLine {
   public static void main(String[] args) {
          List<String> list = Arrays.asList("a", "b", "c");
   }
}
Here we took just 1 line to declare, initialize list and add 3 values in it using Anonymous inner class.

Summary >
So, in this tutorial we did following >
1)  Anonymous inner class / double brace initialization to declare, Initialize and add value in ArrayList in single line.
ArrayList<String> arrayList = new ArrayList<String>() {{
          add("a");
          add("b");
          add("c");
          }};
   }

2) And Arrays.asList to declare, Initialize and add value in List in single line.

List<String> list = Arrays.asList("a", "b", "c");  


Inner class/ nested class, static, local and anonymous inner class in java


Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.


RELATED LINKS>


ArrayList in java



LinkedList in java


Set >

HashSet in java




Map >

HashMap in java


Labels: Core Java
eEdit
Must read for you :