我是一个糟糕的程序员,但我需要一些帮助,因为我一直在拖延建立一个应用程序。 (请注意第一次尝试时缺乏细节感到抱歉
我创建了ArrayList
myObject
个拥有自己属性的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
属性工作正常而不是{{1}}(这是一个数组变量)的任何想法?
谢谢
答案 0 :(得分:3)
要复制数组元素而不是保存数组对象的引用,可以执行此操作。
matrix = Arrays.copyOf(other.matrix, other.matrix.length);