Android - 是否有等同于 Objective-C 语言文字的 @{@"key":@"value"}

Android - is there an equivalent of Objective-C language literals like @{@"key":@"value"}

我要回到 Android 开发中并且很感兴趣 if there's a shorthand way of creating data structures, like arrays, dictionaries, etc. 如果我没记错的话,原语在 Java 中是自动的 boxed/unboxed,但我不是确定更高级的数据结构

在objective-c我可以做到

//NSNumber
@(1)
//dictionary
@{@"key":@"value"}
//array
@[one,two,three]

Android/Java 等价物是什么?

如果需要,

1 可以解释为数字,例如:

if (new Integer(1)==1)  //autoboxing/unboxing
...

Java里面没有字典,但是有HashMap之类的Map。但我不知道如何用这么短的一对 k/v 创建地图。您必须创建一个 HashMap 的新实例,然后添加一个 k/v 如:

new HashMap<String,String>().put("key","value");

至于数组:

new String []{"one","two","three"};

基元像

一样自动装箱
Integer val = 1;

至于数组,您可以内联创建它们

String[] array = {"one", "two", "three"}

但是要将数组传递给方法,您需要显式使用 new

print(new String[] {"one", "two", "three"})

不幸的是 Java 没有任何 shorthand 用于内联 HashMap(字典)创建,但您可以使用 Guava

ImmutableMap.of("k1", "v1", "k2", "v2");

这里有一个例子。

整数 = new Integer(1); number.intValue();

HashMap mHashMap= new HashMap(); mHashMap.put("key","value");

ArrayList mArray = new ArrayList(); mArray.add("value1");