creating and initializing List in same time
Sometime we want to create and initialize List like ArrayList or LinkedList in one line much like creating array and initializing it on same line. If you look Array on Java programming language you can create and initialize both primitive and object array e.g. String array very easily in just one line but in order to create a List equivalent of that array, you need to type lot of code. This is also one of the tricky Java question some time appears in Interview as Write Java code to create and initialize ArrayList in same line. In this Java tips we will see this trick which allow you to create and initialize List much like an Array. This tip can also save lot of time while creating test program or quickly trying some stuff.
Java Tip to create and initialize List in one line
In our post 3 ways to convert Array to ArrayList in Java, we have discussed about Arrays.asList() method. You can use Arrays.asList() method to create and initialize List at same line. java.util.Arrays class act as bridge between Array and List in Java and by using this method you can quickly create a List from Array, which looks like creating and initializing List in one line, as shown in below program.
So this was our Java tip to create and initialize List in same line. Just remember that Arrays.asList() return java.util.List and not ArrayList or LinkedList. Another worth noting point is that List returned by Arrays.asList() is a fixed length list which doesn't allow you to add or remove element from it. add() and remove() method will throw UnSupportedOperationException if you try to add or remove element from List. Some program mistook this List as read only List, which it is not because it allows set() operation which can be used to change element in List. Only legitimate way to create read only Collection is Collections.unmodifiableXXX() method.
That's all on this Java tip about how to create and initialize List in same line in Java. This is a great tip which can save lot of coding time if you frequently create and initialized List with test data.
Other Java Collection tutorials from java67 blog