Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a map as constant in java

Tags:

java

android

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?

like image 832
Wouter Avatar asked Jun 26 '11 14:06

Wouter


People also ask

How do you define a constant in Java?

To make any variable a constant, we must use 'static' and 'final' modifiers in the following manner: Syntax to assign a constant value in java: static final datatype identifier_name = constant; The static modifier causes the variable to be available without an instance of it's defining class being loaded.

How do you define a map in Java?

A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction.

Can a HashMap be static in Java?

2. The Static Initializer for a Static HashMap. The advantage of this kind of initialization is that the map is mutable, but it will only work for static.


1 Answers

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);
}
like image 194
JB Nizet Avatar answered Oct 16 '22 12:10

JB Nizet