Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2006

Tip: Looking for answers? Try searching our database.

Creating a HashMap and Passing It As a Parameter in One Step

Thread view: 
Hal Vaughan - 28 Sep 2006 06:37 GMT
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?

Second, is there a way I can create a HashMap the same way, with just one
line, specifying 2-3 keys and their values?

Thanks!

Hal
Karl Uppiano - 28 Sep 2006 07:04 GMT
>I don't know what this is called, but I know if I have a method like this:
>
[quoted text clipped - 10 lines]
> First, is there a name for creating an object like this just to pass as a
> parameter?

Anonymous? I am not aware of a word for it.

> Second, is there a way I can create a HashMap the same way, with just one
> line, specifying 2-3 keys and their values?

java.util.HashMap has four constructors, only one of which can initialize
the HashMap, and that takes another Map as an argument. So the short answer
would be no, although you could create a class that extends HashMap, or
simply implements Map, that has a constructor that does what you want. With
variable parameter lists, you can enter as many key/value pairs as you want.
Michael Rauscher - 28 Sep 2006 07:33 GMT
Hal Vaughan schrieb:
> I don't know what this is called, but I know if I have a method like this:
>
[quoted text clipped - 13 lines]
> Second, is there a way I can create a HashMap the same way, with just one
> line, specifying 2-3 keys and their values?

E.g.

public class Maps {
    public static final <K,V> HashMap<K, V> asHashMap( K[] keys,
                                                       V[] values ) {
        HashMap<K, V> result = new HashMap<K, V>();
        if ( keys.length != values.length )
            throw new IllegalArgumentException();

        for ( int i = 0; i < keys.length; i++ )
            result.put( keys[i], values[i] );
        return result;
    }

    public static final <K,V> Map<K, V> asMap( K[] keys, V[] values ) {
        return asHashMap( keys, values );
    }
}

Now you can do something like this:

HashMap<String, Integer> map = new HashMap<String, Integer>(
        Maps.asMap(new String[]{"A","B","C"}, new Integer[]{1,2,3})
);

Or even simpler:

HashMap<String, Integer> map = Maps.asHashMap( ... );

Bye
Michael
Mike Schilling - 28 Sep 2006 07:41 GMT
>I don't know what this is called, but I know if I have a method like this:
>
[quoted text clipped - 10 lines]
> 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");
Doug Pardee - 28 Sep 2006 21:49 GMT
> is there a way I can create a HashMap the same way, with just one
> line, specifying 2-3 keys and their values?

setValues(new HashMap(){{put("a","value-a"); put("c","value-c");}});

Yes, it's a messy syntax with parentheses, curly braces, and semicolons
scattered about willy-nilly.

The way that this works is that the statements inside of the second set
of curly braces constitute the "instance initializer" for the anonymous
subclass of HashMap. It's kind of like a constructor with no
parameters.

See section 8.6 of the Java Language Spec (3rd ed.):
http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.6
ddimitrov - 01 Oct 2006 01:28 GMT
I find myself using this every now and then:

http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#singletonMap(
java.lang.Object,%20java.lang.Object
)


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.