Collections FrameworkJava-Collection-Examples

How to create a list with data without using list.add multiple times

Posted On
Posted By admin

In this blog post, I will be explaining how you can easily create a List of elements with some data. Consider the following code snippet:


public static void main(String[] args) {
List<Integer> input = new ArrayList<Integer>();
input.add(3);
input.add(9);
input.add(5);
input.add(15);
input.add(11);

}

 

The code above creates a new ArrayList called input. It invokes the add method multiple times in order to add data to this list. This code does not look very clean. The above code can be re-written as follows:


List<Integer> input = Arrays.asList(3,9,5,15,11);

Here, the Arrays.asList method is invoked.  The Arrays class has methods for manipulating arrays. It also has the asList method. This returns a List which is backed by the specified array.So in this case, the  Arrays.asList returns an ArrayList that has the elements specified.

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment