是否有一种简单的方法来交换列表中的2个子列表。 例子:交换列表中的子列表<MyObject>
[0 1 2 3 4 5 6 7 8 9 10 11] --> [0 1 8 9 10 4 5 6 7 2 3 11]
--> Sublist1= [2 3]
--> Sublist2= [8 9 10]
是否有一种简单的方法来交换列表中的2个子列表。 例子:交换列表中的子列表<MyObject>
[0 1 2 3 4 5 6 7 8 9 10 11] --> [0 1 8 9 10 4 5 6 7 2 3 11]
--> Sublist1= [2 3]
--> Sublist2= [8 9 10]
如果你是好使用索引,这可以通过使用子列表功能,多个文件,并通过创建一个新的列表对象,如下图所示做...
List<Integer> newList = new ArrayList<Integer>(myList.subList(0, 4));
newList.addAll(myList.subList(7, 9));
newList.addAll(myList.subList(4, 7));
newList.addAll(myList.subList(9, 12));
在这里,我们从指数4交换到6索引7至8
如果您只想使用元素来完成此操作,请首先使用元素查找subList的索引并使用上述过程。
不要误会与子列表功能endIndex的... 的fromIndex - 低端点(包括)subList的 toIndex - 高点(不包括)子表 的,所以如果你在子列表中提到7,9功能就意味着从指数7至低于指数元素的所有元素9.
这很容易,但也不短:
static <E> void swapSubList(List<E> list, int first1,int last1, int first2, int last2){
for (int i=first1, j=first2; i<=last1 || j<=last2; i++, j++) {
if(i<=last1 && j<=last2) {
Collections.swap(list, i, j);
}
else if (i>last1){
E temp = list.remove(j);
list.add(i, temp);
}
else {
E temp = list.remove(i);
list.add(j, temp);
}
}
}
如果你不希望创建一个新的集合。
使用Util.Collections.swap
http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#swap(java.util.List,INT,INT)
还应该注意的是,您正在创建一个新列表,而不是对现有列表中的元素进行就地交换。 – 2013-05-04 14:18:17
是的,我已经记下了这一点...... – Buddha 2013-05-04 14:36:55
我仍然认为使用交换是一个更好的选择,但这种解决方案应该工作。 – Bill 2013-05-04 14:38:09