Android数组以字符串为索引的数组

时间:2018-12-04 19:26:09

标签: android multidimensional-array

我正在寻找确实很简单的东西,但我不知道这样做的最佳方法。

我可以有2个字符串数组(开始时我不知道大小),其中包含以下内容:

down[0]:"file1"
down[1]:"file2"
...
up[0]:"file3"
up[1]:"file4"
...

但是我希望它们像在同一数组中一样

array["down"][0]:"file1"
array["down"][1]:"file2"
array["up"][0]:"file3"
array["up"][1]:"file4"

并使用以下命令插入数据

array[mykey].put(filename);

并使用以下命令遍历数据:

for (String st : array["down"])
...
for (String st : array["up"])
...

感谢您的想法。

2 个答案:

答案 0 :(得分:1)

听起来您想要MutableMap<String, MutableList<String>>。例如,在Kotlin中:

val data = mutableMapOf(
  "down" to mutableListOf("file1", "file2"),
  "up" to mutableListOf("file3", "file4")
)

然后您就可以访问:

data["down"].forEach { file ->
  // do something with file
}

或将其更改为:

data["down"].add("file5")

对于Java,您必须更加冗长,但是您可以实现类似的结果:

Map<String, List<String>> data = new HashMap<>();

List<String> downList = new ArrayList<>();
downList.add("file1");
downList.add("file2");
data.put("down", downList);

List<String> upList = new ArrayList<>();
upList.add("file3");
upList.add("file4");
data.put("up", upList);

然后:

for (String file : data.get("down")) {
  // do something with file
}

或将其更改为:

data.get("down").add("file5");

答案 1 :(得分:0)

如果您正在使用Kotlin,可以这样做

val data : MutableMap<String,MutableList<String>> = mutableMapOf()
data["up"] = mutableListOf()
data["down"] = mutableListOf()

// add file to up
data["up"]?.add("file1")

// get the first up
val firstUp = data["up"]?.get(0)

// map over all the ups if the are there
data["up"]?.forEach { str ->

    }
相关问题