[英]Do I need to new ArrayList in loop every time?
Here, I created a new 2D ArrayList and sort it. 在这里,我创建了一个新的2D ArrayList并对其进行排序。
//1. sort list, based on col 0.
//list : List<List<Integer>>
List<ArrayList<Integer>> sortedList = new ArrayList<ArrayList<Integer>>();
for(int i = 0; i < list.size(); i++){
sortedList.add(new ArrayList<Integer>(list.get(i))); //===> question for this line!
}
Collections.sort(sortedList, new Comparator<ArrayList<Integer>>() {
@Override
public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {
return o1.get(0).compareTo(o2.get(0));
}
});
I have a question, for my question line. 我有一个问题要问我的问题。 (see arrow above), do I need to "new" it as I did, or I can just call
(请参见上面的箭头),是否需要像以前一样“重新”添加,或者我可以致电
sortedList.add(list.get(i));
The difference between your two approaches are in the way of how the references are. 两种方法之间的区别在于引用的方式。 In general both should work.
一般来说,两者都应该起作用。
In your first approach you have created a copy of the 2D list, meaning changes to the old list would not affect your sorted list. 在第一种方法中,您创建了2D列表的副本,这意味着对旧列表的更改不会影响您的排序列表。 The first way is more secure.
第一种方法更安全。
In your second approach you have created a shallow copy of the 2D list, meaning if you would change a sub list of your sorted list, these changes would affect the original list and the other way around. 在第二种方法中,您创建了2D列表的浅表副本,这意味着如果您要更改排序列表的子列表,这些更改将影响原始列表,反之亦然。 The second way is more memory efficient and faster.
第二种方法是提高内存效率和速度。
Based on your program above,you declared sortedList as a list of arraylists: List> sortedList = new ArrayList>() 根据上面的程序,您将sortedList声明为arraylists的列表:List> sortedList = new ArrayList>()
SortedList will expect a new ArrayList of type Integer or a reference of ArrayList of type integers SortedList将期待一个新的Integer类型的ArrayList或整数类型的ArrayList的引用
If you want your sortedList to contain a new Array List of Integers for each iteration do the following; 如果要让sortedList为每次迭代包含一个新的整数数组列表,请执行以下操作;
for(int I=0 I<Iist.size I++){
List<Integer> ints = new ArrayList<Integer>();
ints.add(list(I));
sortedList.add(ints);
} }
If you want your sortedList to contain only reference of ArrayList of Integers do the following: Asssuming the list object you are iterating over is of type ArrayList,you can just do sortedList.add(list) 如果要让sortedList仅包含Integer的ArrayList的引用,请执行以下操作:假设您要遍历的list对象的类型为ArrayList,则只需执行sortedList.add(list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.