Wednesday 20 January 2016

How to declare and initialize a List (ArrayList and LinkedList) with values in Java

Initializing a list while declaring is very convenient for quick use, but unfortunately, Java doesn't provide any programming constructs e.g. collection literals, but there is a trick which allows you to declare and initialize a List at the same time. This trick is also known as initializing List with values. If you have been using Java programming language for quite some time then you must be familiar with syntax of array in Java and how to initialize an array in the same line while declaring it as shown below:

String[] oldValues = new String[] {"list" , "set" , "map"};

or even shorter :

String[] values = {"abc","bcd", "def"};

Similarly, we can also create List  and initialize it at the same line, popularly known as initializing List in one line example. Arrays.asList() is used for that purpose which returns a fixed size List backed by Array. By the way don’t confuse between Immutable or read only List which doesn’t allow any modification operation including set(index) which is permitted in fixed length List.Here is an example of creating and initializing List in one line:
Read more »

No comments:

Post a Comment