【问题标题】:arraylist of objects, adding objects对象的arraylist,添加对象
【发布时间】:2015-04-20 03:42:40
【问题描述】:

我是一个糟糕的程序员,但我需要一些帮助来解决我一直拖延构建的应用程序。 (请注意,第一次尝试时缺少细节,抱歉

我创建了一个 ArrayList 的 myObjects,它们有自己的属性。当我创建 myObject 类时,我创建了一个初始化程序,以便我可以将 myObject 添加到其中的 ArrayList 中。我让它工作了,但我遇到了问题,因为当我遍历我的代码时,对象的属性被覆盖了。这是一个简化的例子:

myOjbect newMyObject = new myObject
List<myOject> listOfObjects = new ArrayList<myObjet>();

try {

    // go through a text file, set some properties of my object...
     myArrayValue = some text input //(sorry i didnt want to put the whole code as its sloppy, but it does return an array) 
     myObject.matrix = myArrayValue; // this value changes as I go through the text file, but in the listOfObects, only the last value is saved to each item in the list
    SetStartDate(somestring1); // another constructor/initializer (sorry i forget the correct terminology) I added to the 'myObject' class. This property sets correctly in the list
    listOfObjects.add(new myObject(newMyObject));

那么在我的myObject 类中有这个初始化器:

public myObject(myObject other){
    matrix = other.matrix;
    startDate = other.startDate;
    // TODO add all the properties here, so that they get copied
}

public SetStartDate(string inputText){
startdate = inputText // or something like that, I dont have the code on this computer
}

所以startDate 属性正在工作,当我遍历项目列表但设置matrix 属性时,我总是以主脚本中的最后一个属性值作为每个项目的属性值在列表中。

知道为什么startDate 属性可以正常工作,而matrix(它是一个数组变量)不能正常工作吗?

谢谢

【问题讨论】:

  • 你在做什么public myObject(myObject other)??发送同一类的对象并制作另一个对象?参数化构造函数是发送值并初始化其变量。
  • 发布您的实际代码有助于了解问题所在。
  • - loop through some code, set some properties of my object... 这个循环中有什么代码?
  • 我们需要方式更多细节来回答这个问题。关于您的代码实际是什么以及它实际在做什么的信息太多了,如果没有实际的源代码,我们将错过这些信息。

标签: java object arraylist


【解决方案1】:

要复制数组元素而不是保存数组对象的引用,您可以这样做。

matrix = Arrays.copyOf(other.matrix, other.matrix.length);

【讨论】:

  • 这怎么可能是答案?我们甚至不知道matrix 实际上是什么!当他们谈论的只是ArrayList时,你为什么认为他们试图复制一个数组?
  • @Makoto,“矩阵(这是一个数组变量)”,我猜他正在尝试按照 C++ 的复制构造函数编码技术进行编码。显然问题是,它的矩阵数组没有被保存。你能帮我提一下我哪里做错了吗?
  • 谢谢,我认为这是问题所在。虽然它是一个深数组,但我猜我需要循环遍历它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-12
  • 2016-03-12
  • 1970-01-01
  • 1970-01-01
  • 2011-12-24
相关资源
最近更新 更多