简体   繁体   English

在java中将映射定义为常量

[英]Define a map as constant in java

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. 对于我的Android应用程序,我需要在一个常量中定义一些键,我认为最好的方法是使用地图。 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. 由于我的目标是Android,因此Bundle也可能是一种选择。

I have a list of keys like: 我有一个键列表,如:
"h" = "http" “h”=“http”
"f" = "ftp" “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. 基本上该程序是读取QR代码(以防止代码变得太大,我使用的是超短键),获取这些密钥,并且必须将它们转换为有用的东西,在我的情况下是协议。

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". 我正在尝试定义一个名为KEY_PROTOCOLS的常量,我认为这应该是一个Map,所以稍后我可以调用类似KEY_PROTOCOLS.get(“f”)的东西来获得属于键“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? 我怎样才能做到这一点?

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);
}

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 http://www.glenmccl.com/tip_003.htm

On android: 在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;
    }

This would work. 这会奏效。

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

static {
   map.add("ftp", "ftp");
   ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM