Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct an ArrayList of strings in Java as simple as one can in Javascript

In JavaScript I can build an Array of string values like:

var stuff = new Array('foo','bar','baz','boz','gaz','goz');

or even easier

var stuff = 'foo,bar,baz,boz,gaz,goz'.split(',');

In Java it seems overly verbose and complex... is there an easier way than this?

ArrayList<String> stuff = new ArrayList<String>();
stuff.add("foo");
stuff.add("bar");
stuff.add("baz");
stuff.add("boz");
stuff.add("gaz");
stuff.add("goz");

In my actual scenario I have 30-40 items going into the ArrayList... I figure there just has to be an easier way! What is the obvious bit I'm overlooking?

like image 737
danny Avatar asked Jul 07 '10 19:07

danny


People also ask

Can we use ArrayList in JavaScript?

JavaScript does not support associative arrays. You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers.

What is ArrayList String in Java?

ArrayList in Java is used to store dynamically sized collection of elements. Contrary to Arrays that are fixed in size, an ArrayList grows its size automatically when new elements are added to it. ArrayList is part of Java's collection framework and implements Java's List interface.

How do you create an ArrayList from a List in Java?

Convert list To ArrayList In Java. ArrayList implements the List interface. If you want to convert a List to its implementation like ArrayList, then you can do so using the addAll method of the List interface.


2 Answers

List<String> strings = Arrays.asList(new String[] {"foo", "bar", "baz"}); or List<String> strings = Arrays.asList("foo,bar,baz".split(","));

like image 168
Igor Artamonov Avatar answered Sep 28 '22 08:09

Igor Artamonov


Arrays.asList() is a good way to get a List implementation, though it is technically not an ArrayList implementation, but an internal type.

If you truly need it to be an ArrayList you could write a quick utility method:

public static List<String> create(String... items) {
    List<String> list = new ArrayList<String>(items.length);
    for (String item : items) {
        list.add(item);
    }

    return list;
}
like image 20
Jeff Avatar answered Sep 28 '22 07:09

Jeff