【问题标题】:Java - set data from 1 List to another [duplicate]Java - 将数据从1个列表设置到另一个[重复]
【发布时间】:2015-11-20 22:34:43
【问题描述】:

我的程序中有 2 个列表;列表之一已经有数据。我需要创建一个新列表并从以前的列表中传递一些数据。

以下是我使用的代码:

List<Class1> result = function();
List<Class2> newList = new ArrayList<Class2>();

for(int i=0; i < result.size(); i++) {
     newList.get(i).setValue(result.get(i).getValue());
     //setValue() is setter function in Class2
     //getValue() is getter function in Class1
    }
  return newList;

当我尝试运行代码时,我在此特定行中遇到错误:

newList.get(i).setValue(result.get(i).getValue());

错误是:

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
java.util.ArrayList.rangeCheck(ArrayList.java:635)
java.util.ArrayList.get(ArrayList.java:411)

我该如何解决这个问题?需要一些帮助。

【问题讨论】:

  • 您刚刚创建了一个空的newList,其中没有Class2 对象。你期望newList.get(0) 准确返回什么?

标签: java


【解决方案1】:

假设您有一个名为obj1obj2 的变量。 obj1 是某个对象的一个​​实例。 obj2 为空。然后将obj2 的变量设置为obj1 变量。你得到了什么? NullPointerException 因为obj2 为空。

要解决这个问题,您必须创建一个对象。例如在for 循环中(在您的newList.get(...) 方法之前)。您想要复制对象或复制一些变量。为此,请在 for 循环中执行类似的操作。

newList.set( i, result.get(i) ); // if you want to copy the class

newList.set( i, new Class2(/* ... */) );
newList.get(i).setValue( result.get(i).getValue() ); // to copy variable

@Edit 仅当Class2 扩展Class1 时,您才能使用第一种方法(newList... = 结果...)

【讨论】:

  • 就我而言,第二种方法是适用的。但是,我认为 newList.get(i) = new Class2(/* ... */) 不会起作用。您能否提出一些建议,以便我可以将一个班级成员从一个列表复制到另一个? @mibac
  • @Arnab 你为什么这么认为?代替/* ... */,您只需放置构造函数参数。
  • 我确实尝试过使用构造函数参数。它生成的错误是“newList.get(i)”,错误是“赋值的左侧必须是变量”。
  • 感谢修改。但是,使用新代码,我现在收到“IndexOutOfBoundsException:Index:0,Size:0”错误。任何想法,为什么会发生这种情况? @mibac
  • 关于这个问题还有什么其他建议吗??
猜你喜欢
  • 2020-11-03
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
  • 2019-02-02
  • 2012-01-06
  • 1970-01-01
  • 2011-05-10
相关资源
最近更新 更多