java 在java中将映射定义为常量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6484604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:03:55  来源:igfitidea点击:

Define a map as constant in java

javaandroid

提问by Wouter

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.

对于我的 Android 应用程序,我需要在单个常量中定义一些键,我认为最好的方法是使用地图。但不确定这是否真的是要走的路,以及如何正确地做到这一点。由于我的目标是 Android,Bundle 也可能是一种选择。

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

我有一个键列表,如:
“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".

我正在尝试定义一个名为 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?

我怎样才能做到这一点?

回答by JB Nizet

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

回答by Blundell

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

回答by Andrew

This would work.

这会奏效。

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

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

回答by diyism

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