我试图将静态数据插入Java中的 HashMap ,如下所示:
HashMap<String,String[]> instruments = new HashMap<String, String[]>();
instruments.put("EURUSD", {"4001","EURUSD","10000","0.00001","0.1","USD"});
但是编译器不喜欢它。我发现将数据插入HashMap的唯一方法是分别声明字符串数组,然后将其放入HashMap中,就像这样
String[] instruDetails = {"4001","EURUSD","10000","0.00001","0.1","USD"};
instruments.put("EURUSD", instruDetails);
但它表达力不强,难以维持
所以我的问题是,有没有办法在一个步骤/行中执行put()
操作和字符串数组声明?
答案 0 :(得分:12)
这样做:
instruments.put("EURUSD", new String[]{"4001","EURUSD","10000","0.00001","0.1","USD"});
答案 1 :(得分:8)
要在一个句子中全部使用,请使用双括号初始化: -
HashMap<String,String[]> instruments = new HashMap<String, String[]>() {
{
put("EURUSD", new String[]{"4001","EURUSD","10000","0.00001","0.1","USD"});
put("EUR", new String[]{"4001","EURUSD","10000","0.00001","0.1","USD"});
}
};
答案 2 :(得分:6)
我认为你已经有了可行的方法。但原因是
instruments.put("EURUSD", {"4001","EURUSD","10000","0.00001","0.1","USD"});
不起作用是因为{"4001","EURUSD","10000","0.00001","0.1","USD"}
。 {}
是Java数组中用于初始化的语法糖或快捷方式。它带有一个约束,它总是必须与数组声明语句一起使用,否则它是语法错误。
数组声明语句,如
String[] array = {"1", "2"};
这样Java知道它需要为你创建的数组实际上是String
类型的元素。
如果您违反以上声明如下
String[] array;
array = {"1", "2"};
它无法编译。
使用new String[]{"4001","EURUSD","10000","0.00001","0.1","USD"}
,编译器知道它必须实例化一个新数组,其元素类型为String
(new String[]
)并使用您提供的值初始化新实例化的数组( {"4001","EURUSD","10000","0.00001","0.1","USD"}
)。