1

我的函数原型:

private String buildParamaters(Object[][] arguments)

此方法构建一个 URL。

参数的示例值可能是:

List<String> items = ...
new Object[][] {{"key1", 25}, 
                {"key2", "a string"},
                {"key3", items}}

因此,第一个维度始终是字符串,但第二个维度可以是一系列类型。

而不是 Object[][] 我如何定义这个参数,以便第一个维度是一个字符串?还有一个额外的问题:除了将第二维定义为泛型类型之外,还有其他实用的替代方法吗?

4

4 回答 4

6

用自定义对象数组替换数组数组,如下所示:

public class KeyedItem {
     private final String key;
     private final Object value;
     public KeyedItem(String key, Object value) {
         this.key = key;
         this.value = value;
     }
}
...
private String buildParamaters(KeyedItem[] arguments) {
    ...
}
...
KeyedItem[] arguments = new KeyedItem[] {
    new KeyedItem("key1", 25)
,   new KeyedItem("key2", "a string")
,   new KeyedItem("key3", items)
};
于 2013-05-03T13:33:17.533 回答
0

您确定不想为此使用 aHashMap吗?例子:

HashMap<String, Object> items = new HashMap<String, Object>();
items.put("key1", 25);
于 2013-05-03T13:34:50.140 回答
0

您正在寻找的是字符串和对象之间的映射,因此类似于:

Map<String, Object>

Or, instead of Object, you may want to place a type parameter if this is happening in a type-parameterized method or class.

于 2013-05-03T13:35:49.767 回答
0

Since you want to build a URL, you could also use a Multimap from Guava's collections, which allows you to have several values for one key, as can happen with query parameters:

Multimap<String, Object> params = HashMultimap.create();
params.put("key1", "value1");
params.put("key2", 2);
params.put("key2", 3);
于 2013-05-03T14:06:11.113 回答