【问题标题】:How can I get arraylist out of the for loop?如何从 for 循环中获取 arraylist?
【发布时间】:2015-07-17 10:53:58
【问题描述】:

我有

List<ABC> abcList = new ArrayList<ABC>();
ABC abc = new ABC();

for (int i = 0; i < abcList.length; i++) {
    abc.setX(5) 
    abc.setY(5-10) // just an example to easy to understand
    abcList.add(abc)
}
System.out.println(Integer.toString(offsetList.get(0).getY()));

我希望结果是 -5,但日志打印 0 并且剩余对象的结果相同。我正在学习java,请告诉我如何将arraylist从for循环中取出?

【问题讨论】:

  • offsetList和abcList有什么关系?这只是一个错字吗?
  • 是的,它是。我编辑了它,对不起:D
  • 请说明您打算实现的目标,至少对我而言,这很令人困惑。
  • 另外,您多次添加同一个对象 ABC 对象,这是您不断更改 X 和 Y 的同一个实例,不知道您想要实现什么,但 new ABC() 应该在循环中.如果您刚刚创建了一个空列表,它应该如何循环到 abcList.length
  • 你的程序如何使用abcList.length进行编译;你需要使用abcList.size();

标签: java for-loop


【解决方案1】:

你必须每次都重新初始化你的 abc 变量。

你的 arrayList 在开始时也是空的。它永远不会进入 for 循环。

List<ABC> abcList = new ArrayList<ABC>();

for (int i = 0; i < 10; i++) {
    ABC abc = new ABC();//You have to re-initialise your variable each time.
    abc.setX(i);
    abc.setY(i - i * 2); 
    abcList.add(abc);
}
System.out.println(abcList.get(0).getY());

【讨论】:

    【解决方案2】:

    只需删除for loop,您就会在那里得到预期的答案。

    要向list 添加单个元素,您不需要for loop

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-25
      • 1970-01-01
      • 2014-06-10
      • 1970-01-01
      • 2017-05-18
      • 2017-09-17
      • 2011-07-23
      • 1970-01-01
      相关资源
      最近更新 更多