5

我正在尝试将静态数据插入到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()在一步/行中进行操作和字符串数组声明?

4

3 回答 3

12

这将做到:

instruments.put("EURUSD", new String[]{"4001","EURUSD","10000","0.00001","0.1","USD"});
于 2012-10-04T17:46:07.987 回答
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"});
     }
 };
于 2012-10-04T17:46:44.687 回答
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"}

于 2012-10-04T18:06:24.533 回答