【问题标题】:How to create objects dynamically during runtime Java如何在运行时 Java 中动态创建对象
【发布时间】:2019-04-11 13:08:36
【问题描述】:

我正在尝试制作一个需要按照以下内容动态创建 ArrayLists 的程序:

for (int i = 0; i < arbitraryInt; i++){
    //code to make 5 new arraylists
}

但是我似乎找不到任何可以完成此任务的方法。

编辑:我正在尝试为我的 APCS 课程制作柱状密码。该密码要求我将任意长度的字符串转换为网格。在这种情况下,每个数组列表都是一列。所以更具体地说,我的代码看起来有点像这样:

String encode = "somethingsomethingyadayadayada";
int x = 0, y = 0;

for (int i = 0; (i*i) < encode.length(); i++){
    y = i;
    x = i-1;
}
for (int i = 0; i < x; i++){
    //make an arraylist
}

这是更好的@Kartic 吗?我试图保持它不具体,以防止我的帖子成为代码转储。

【问题讨论】:

  • 嗯,你想把它们放在哪里?你想用它们做什么?
  • 使用new ArrayList() 5 次或循环使用有什么问题?或有List&lt;List&lt;Integer&gt;&gt;
  • 在我尝试制作的最终版本中,arraylists 的数量将根据某些参数而有所不同。
  • @Sumtinlazy 有哪些参数?请完成你的问题..“沿着这条线”是不够的
  • 我得到了答案,为你更新,宝贝。

标签: java object dynamic


【解决方案1】:

一种可能的解决方案是将列表存储在列表中:

List<List<Integer>> listOfLists = new ArrayList<>();
for (int i = 0; i < arbitraryInt; i++){
    listOfLists.add(new ArrayList<>());
}
// get third list
List<Integer> third = listOfLists.get(2);

【讨论】:

    猜你喜欢
    • 2017-12-28
    • 2011-02-28
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多