Skip to content

Filling ArrayList with one line, sort of

As a follow up to an earlier post on double braces in Java, came up with a short, but ugly way of filling an ArrayList via an array.

String[] ray = {"Hi", "there", "Bob"};
ArrayList<String> lst = new ArrayList<String>() {{
	for (String s: ray) { add(s); }
}}

Of course, at that point you might as well just do this.

ArrayList<String> lst = Arrays.asList(new String[]{"Hi", "there", "Bob"});
Published inCode Tips

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *