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?
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.
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.
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.
List<String> strings = Arrays.asList(new String[] {"foo", "bar", "baz"});
or
List<String> strings = Arrays.asList("foo,bar,baz".split(","));
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With