Re: Creating a HashMap and Passing It As a Parameter in One Step
"Hal Vaughan" <hal@thresholddigital.com> wrote in message
news:k6ydnbvW0-rrwobYnZ2dnUVZ_vydnZ2d@comcast.com...
I don't know what this is called, but I know if I have a method like this:
public void setValues(String[] newValues) {
//Do a bunch of stuff
return;
}
That I can call it by building a String[] within the line that calls it,
like this:
setValues(new String[] {firstString, secondString, thirdString});
First, is there a name for creating an object like this just to pass as a
parameter?
I've seen it called an anonymous array.
Second, is there a way I can create a HashMap the same way, with just one
line, specifying 2-3 keys and their values?
The short answer is "no"; only arrays have this special syntax, probably
because arrays are the only built-in aggregate type. Of course, there's
nothing to stop you from writing a HashMapCreator class, something like (not
compiled or tested, so please ignore any typos)
public class HashMapCreator
{
public static Map create(Object[] params)
{
HashMap map = new HashMap();
for (int i = 0; i < params.length; i+=2)
{
map.put(params[i], params[i+1];
}
return map;
}
}
which lets you write
Map map = HashMapCreator.create(new Object[] {"color", "red", "size",
"XXL"});
In Java 1.5 you can make create a varargs method and make the call just
HashMapCreator.create("color", "red", "size", "XXL");