Monday, March 23, 2020

Using Map in Java

I need to translate some strings (state abbreviations for example) into corresponding integers.  There is a way to use Map to simplify this, but the examples that I am fjnding are less than clear.  There are three different tables that I need to do lookups in, and each table is static.  I am guessing that the method is something like:

public class Lookup {
    public int LookupTable(HashMap(String, Integer) table, String toLookup)
        return (table.get(toLookup));

But how do I statically define the HashMap that I will pass to this method?
This ought to do it, I think.

    Map states = new HashMap();
    states.put("AL", new Integer(1));

But I still get errors  about syntax error on the semicolon on the states.put line.  Every example that I can find looks like this:

    HashMap states = new HashMap();
    states.put(1, "AL");

So why does my put call fail syntactically?  Not in a method.

1 comment:

Rick C said...

When I try HashMap h = new HashMap(), and then your put statement, I get a type safety warning suggesting I use a parameterized HashMap instead.

This compiles OK:

HashMap[String, Integer] h = new HashMap[String, Integer]();
h.put("AL", 1);

only use angle brackets instead of square ones (I didn't want to take the time to find the right markup to display the less than and greater than symbols.)