How to create a list with data without using list.add multiple times
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.
Comments
Post a Comment