The Shortest Way to Fill the Arraylist

What is the shortest way to fill the ArrayList? Something like:

ArrayList<Integer[]> list = new ArrayList<Integer[]>();
list.add({1,10,1,1});
list.add({2,11,1,1});

Or:

ArrayList<Integer[]> list = ({1,10,1,1},{2,11,1,1});
5

4 Answers

How about this shortcut:

List<int[]> list = Arrays.asList( new int[][]{{1,10,1,1}, {2,11,1,1}} );

Using guava

Lists.newArrayList(new int[]{1,2,3}, new int[]{2,4,5}, new int[]{5,6,7});

To fix your first attempt:

ArrayList<Integer[]> list = new ArrayList<Integer[]>();
list.add(new Integer[]{1,10,1,1});
list.add(new Integer[]{2,11,1,1});
List<Integer[]> list = new ArrayList<Integer[]>();
list.add(new Integer[] { 1, 10, 1, 1 });
list.add(new Integer[] { 2, 11, 1, 1 });

Or here is a one-liner:

List<Integer[]> list = Arrays.asList(new Integer[] { 1, 10, 1, 1 }, new Integer[] { 2, 11, 1, 1 });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest