克隆新的对象传递给ArrayList的? [英] Clone new objects to pass to ArrayList?
问题描述
我建立一个Android应用程序,我试图将对象添加到的ArrayList
。我认为这将在的ArrayList
创建对象的副本,然后我可以重用的对象。我意识到这不是案件, ArryList
实际上是引用原始对象。
我真的不知道我怎么会用一个循环中的的onCreate
函数来创建新的对象,这样做的我莫名其妙地需要克隆对象,并把它传递给在的ArrayList
反正这里是我的code:
公共类主要活动扩展{
私人项目myItem =新项目(); btnSave.setOnClickListener(新View.OnClickListener(){
公共无效的onClick(视图v){
alItems.add(myItem);
arrayAdapter.notifyDataSetChanged();
您可以创建一个的 拷贝构造函数
在项目
类,并用它来创建对象的副本。
公共类项目{
私人诠释FIELD1;
公共项目(){} 公共项目(项目项目){
this.field1 = item.field1;
}
}
和使用对象添加到列表: -
alItems.add(新项目(myItem));
I'm building an android app and I was trying to add objects to an ArrayList
. I thought this would create a copy of the object in ArrayList
and then I could reuse the object. I've realized this isn't the case and that ArryList
was actually referencing the original object.
I'm not really sure how I'd use a loop to create new objects in the onCreate
function so do I somehow need to clone the object and pass it to the ArrayList
?
Anyway here's my code:
public class Main extends Activity {
private Item myItem = new Item();
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
alItems.add(myItem);
arrayAdapter.notifyDataSetChanged();
You can create a copy constructor
in your Item
class, and use it to create a copy of your object.
public class Item {
private int field1;
public Item() { }
public Item(Item item) {
this.field1 = item.field1;
}
}
And add your object to list using: -
alItems.add(new Item(myItem));
这篇关于克隆新的对象传递给ArrayList的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!