views:

2967

answers:

6

Can someone please provide an example of creating a Java ArrayList and HashMap on the fly? So instead of doing an add() or put(), actually supplying the seed data for the array/hash at the class instantiation?

To provide an example, something similar to PHP for instance:

$array = array (3, 1, 2);
$assoc_array = array( 'key' => 'value' );

+1  A: 

You mean like this?

public List<String> buildList(String first, String second)
{
     List<String> ret = new ArrayList<String>();
     ret.add(first);
     ret.add(second);
     return ret;
}

...

List<String> names = buildList("Jon", "Marc");

Or are you interested in the ArrayList constructor which takes a Collection<? extends E>? For example:

String[] items = new String[] { "First", "Second", "Third" };
// Here's one way of creating a List...
Collection<String> itemCollection = Arrays.asList(items);
// And here's another
ArrayList<String> itemList = new ArrayList<String>(itemCollection);
Jon Skeet
A slight improvement on Jon's suggestion: works for any number of items: public List<String> buildList(String... items) { return new ArrayList<String>(Arrays.asList(items)); }
Steve McLeod
(The example code could be simplified a little by making use of varags Arrays.asList(); http://stackoverflow.com/questions/258954/java-out-with-the-old-in-with-the-new/635078#635078)
Jonik
I was showing the separate steps to make it obvious how to do things when you'd already got an array.
Jon Skeet
Why not use var-args so you can pass any number of items?
sal
+5  A: 

A nice way of doing this is using Google Collections:

List<String> list = ImmutableList.of("A", "B", "C");

Map<Integer, String> map = ImmutableMap.of(
  1, "A",
  2, "B",
  3, "C");
Steve McLeod
thanks be to varargs
matt b
Yes, I was going to come back and mention Google's collections. They rock :)
Jon Skeet
500kB is a high price to pay just to do that. If the only thing wanted is to fill the Collection on the fly, the accepted answer is IMHO nicest.
Damien B
Another reason to dislike this approach is that it's an immutable list, though I'm guessing (without having read the documentation) that there is a mutable list?
altCognito
It's immutable by design! But yes, there are other options too. If it's immutable you can easily share one instance between threads, and therefore between web requests.500 Kb is a high price to pay. But there are so many other goodies in the Google Collectons, it's worth paying the price.
Steve McLeod
+3  A: 

ArrayLists are straightforward:

List<String> al = Arrays.asList("vote", "for", "me"); //pandering

Taken from comments, note that this returns a fixed size Array$ArrayList, not an ArrayList

Bruno's approach works best and could be considered on the fly for maps. I prefer the other method for lists though (seen above):

Map<String,String> map = new HashMap<String,String>() {
 {
    put("key1", "value1");
    put("key2", "value2");
 }
};
altCognito
be warned, Arrays.asList does not return an java.util.ArrayList but a fixed-size java.util.Arrays$ArrayList!
Carlos Heuberger
Noted, I didn't realize that.
altCognito
stepped into that last week, neither immutable nor a "real" Arraylist...
Carlos Heuberger
+6  A: 

Use a nice anonymous initializer:

List<String> list = new ArrayList<String>() {{
    add("a");
    add("b");
}};

Same goes for a Map:

Map<String, String> map = new HashMap<String, String>() {{
    put("a", "a");
    put("b", "b");
}};

I find this the most elegant and readable.

Other methods demand creating an array first, then converting it to a List - too expensive in my taste, and less readable.

Yuval A
+9  A: 
List<String> list = new ArrayList<String>() {
 {
    add("value1");
    add("value2");
 }
};

Map<String,String> map = new HashMap<String,String>() {
 {
    put("key1", "value1");
    put("key2", "value2");
 }
};
bruno conde
+1, definitely the nicest for maps
altCognito
creating a new class without any diferent functionality...
Carlos Heuberger
These approaches are good. But the contents can be modified after creation. Immutable approachs are sooooo nice!
Steve McLeod
this is sometimes dangerous. you will get a reference to the enclosing class since the anonymous inner class maintains a reference to its parent object. this may cause problems with garbage collection and serialisation.
Andreas Petersson
I do not like double-brace initialization at all. Why create a new (non-static) inner class when a simple initializer will do just as well?
Michael Myers
I've always thought that the double brace approach was nice (esp for GUI construction) - but the comment on the parent object reference is very well made. Proceed with caution here. Might be better to make up a little Map builder class that accepts a vararg of objects (key, value, key value, etc...).
Kevin Day
+2  A: 

for short lists:

    List<String> ab = Arrays.asList("a","b");
Andreas Petersson
only for fixed-size list...
Carlos Heuberger
not really.. from java.util.Arrays.java: public static <T> List<T> asList(T... a) { return new ArrayList<T>(a); }so it just returns a pre-initialized ArrayList
Andreas Petersson
Look further in the source. Arrays has its own internal ArrayList class which doesn't support add() or remove().
Michael Myers
and from the documentation of asList: "Returns a fixed-size list backed by the specified array."
Carlos Heuberger
oh my you're right :) tricky, tricky..
Andreas Petersson