10

For my Android app I've the need of defining some keys in a single constant, and I think the best way to do it is using a map. But not sure whether that's really the way to go, and how to do it correctly. As I'm targeting Android, a Bundle may also be an option.

I have a list of keys like:
"h" = "http"
"f" = "ftp"

Basically the program is to read a QR code (to keep that code from growing too big I'm using super-short keys), gets those keys, and has to translate them to something useful, in my case a protocol.

I'm trying to define a constant called KEY_PROTOCOLS, I think this should be a Map, so later I can call something like KEY_PROTOCOLS.get("f") to get the protocol that belongs to key "f".

Other classes should also be able to import this constant, and use it. So this map has to be populated in the class right away.

How can I do this?

Wouter
  • 2,623
  • 4
  • 34
  • 43

4 Answers4

26

If the constant is shared by several classes, and if you want to make sure this map is not cleared or modified by some code, you'd better make it unmodifiable :

public static final Map<String, String> KEY_PROTOCOLS;

static {
    Map<String, String> map = new HashMap<String, String>();
    map.put("f", "ftp");
    // ...
    KEY_PROTOCOLS = Collections.unmodifiableMap(map);
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 3
    +1 for making it unmodifiable. If the OP is using the Guava libraries, they can also just use `ImmutableMap`. `public static final ImmutableMap KEY_PROTOCOLS = ImmutableMap.of("f", "ftp");` – Tom Jun 26 '11 at 15:21
  • First answer was good, this one even better so that's why this one is my "accepted" answer. Thanks! – Wouter Jul 03 '11 at 15:36
3

Something like this:

  private static final Map<String, String> KEY_PROTOCOLS = new HashMap<String, String>();
 static{
    KEY_PROTOCOLS.put("f", "ftp");
    // More

}

Static Initialisers:

http://www.glenmccl.com/tip_003.htm

Blundell
  • 75,855
  • 30
  • 208
  • 233
0

On android:

@SuppressWarnings("unchecked")
Pair<String,String>[] pre_ips=new Pair[]{new Pair<String,String>("173.194", "0"), new Pair<String,String>("74.125", "96")};
String ip_1_2,ip_3;
for (Pair<String,String> pre_ip:pre_ips)
    {ip_1_2=pre_ip.first;
     ip_3=pre_ip.second;
    }
diyism
  • 12,477
  • 5
  • 46
  • 46
0

This would work.

static Map<String, String> map = new HashMap<String, String>();

static {
   map.add("ftp", "ftp");
   ...
}
Andrew
  • 13,757
  • 13
  • 66
  • 84