是否有使用循环创建多个对象(例如数组)的方法?

问题描述 投票:1回答:1

我有一个包含n个包含名称的元素的数组,对于每个具有索引i的元素,我都需要一个新数组,其数据来自输入。

因此,如果数组为

["Claire", "Luke", "John"] 

我需要三个新数组

String [] Claire = new String [];
String [] Luke = new String [];
String [] John = new String [];

我可以使用for循环吗?什么是更常规/更好的解决方案?

for (int i = 0; i>num; i++) {

    String objectName = someArray[i]; // this new String objectName would be used to as the name of the new Array

    String [] objectName = new String [] //this does not work of course, but the name of the new object needs to be the String objectName

// then I would like to create a new object with the name equaling the String objectName
java arrays loops variables naming
1个回答
0
投票

不,Java不是一种“只是保持运行状态的语句”。

您可能正在寻找Map<String, List<String>或类似的内容:

Map<String, List<String>> addresses = new HashMap<>();
for (String name : someArray) {
    List<String> list = addresses.computeIfAbsent(name, n -> new ArrayList<String>());
    list.add(makeUpAnAddress());
}

现在您有了一张地图,将您的姓名映射到地址列表。请注意,数组是低级的过时构造,列表是“更好的”(它们使用更多的API并且更加灵活)。如果您确实需要,也可以设置Map<String, String[]>,我不会。

© www.soinside.com 2019 - 2024. All rights reserved.