问题描述
我在理解如何复制ArrayList
方面有一个小问题。有我的代码:
public class RecyclerView_Adapter extends RecyclerView.Adapter<RecyclerView_Adapter.recyclerViewHolder>{
private List<Item> list1;
private List<Item> list2;
// with constructor:
public RecyclerView_Adapter(Context context,Arraylist<Item> list1){
this.context = context;
this.list1 = list1;
this.list2 = new Arraylist<>(list1)
}
}
它应该将list1复制到list2对吗? 当我使用此代码时:
Log.i("TAG1",list1.toString());
Log.i("TAG2",list2.toString());
它返回
TAG1 : []
TAG2 : []
TAG1: [com.example.something1290,com.example.something1267,com.example.something1298] (some data)
TAG2: [] // <-- still returns empty array why?
当我使用此代码时,不在构造器中,而是在其他地方,那么它在两个数组中返回相同的数据。
所以问题是:
为什么在构造函数中我无法将list1复制到list 2,但是必须以其他方法执行此操作?
编辑:
看起来像:
// with constructor:
public RecyclerView_Adapter(Context context,Arraylist<Item> list1){
this.context = context;
Log.i("TAG1",list1.toString());
this.list1 = list1;
this.list2 = new Arraylist<>(list1)
// It can return an empty array like:
TAG1 : []
}
}
但是在这种情况下:
// with constructor:
public RecyclerView_Adapter(Context context,Arraylist<Item> list1){
this.context = context;
this.list1 = list1;
Log.i("TAG1",list1.toString());
this.list2 = new Arraylist<>(list1)
// It should return an array with data,but return empty array again
TAG1 : []
}
}
解决方法
首先,您要创建一个在另一个列表中传递的列表。那将不会产生另一个副本,而是会在其中插入另一个列表而不进行复制。您可以使用ArrayList.clone()
或ArrayList.addAll()
方法之类的方法来复制arraylist
// with constructor:
public RecyclerView_Adapter(Context context,Arraylist<Item> list1){
this.context = context;
Log.i("TAG1",list1.toString());
this.list1 = list1;
this.list2 = new Arraylist<>().addAll(list1) // or this.list2 = list1.clone();
// It will return the contents of list1 copied to list2 array like:
}