Can someone please provide an example of creating a Java ArrayList
and HashMap
on the fly? So instead of doing an add()
or put()
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);
List<String> list = new ArrayList<String>() {
{
add("value1");
add("value2");
}
};
Map<String,String> map = new HashMap<String,String>() {
{
put("key1", "value1");
put("key2", "value2");
}
};
Arrays can be converted to List
s:
List<String> al = Arrays.asList("vote", "for", "me"); //pandering
Note that this does not return an ArrayList
but an arbitrary List
instance (in this case it’s an Array.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");
}
};
for short lists:
List<String> ab = Arrays.asList("a","b");
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");
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.