您的位置:首页 > 其它

操作集合工具类:Collections

2015-04-27 22:49 483 查看
Collections是常用的操作Set、List、Map的工具类。提供了大量方法对集合元素进行排序、查询和修改等操作,还提供了将集合对象设置为不可变、对集合对象实现同步控制等方法。

reverse 反转:

/**
* Reverses the order of the elements in the specified list.<p>
*
* This method runs in linear time.
*
* @param  list the list whose elements are to be reversed.
* @throws UnsupportedOperationException if the specified list or
*         its list-iterator does not support the <tt>set</tt> operation.
*/
public static void reverse(List<?> list) {
int size = list.size();
if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
swap(list, i, j);
} else {
ListIterator fwd = list.listIterator();
ListIterator rev = list.listIterator(size);
for (int i=0, mid=list.size()>>1; i<mid; i++) {
Object tmp = fwd.next();
fwd.set(rev.previous());
rev.set(tmp);
}
}
}


shuffle 随机排序“洗牌”:

public static void shuffle(List<?> list, Random rnd) {
int size = list.size();
if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
for (int i=size; i>1; i--)
swap(list, i-1, rnd.nextInt(i));
} else {
Object arr[] = list.toArray();

// Shuffle array
for (int i=size; i>1; i--)
swap(arr, i-1, rnd.nextInt(i));

// Dump array back into list
ListIterator it = list.listIterator();
for (int i=0; i<arr.length; i++) {
it.next();
it.set(arr[i]);
}
}
}


sort 排序:调用了Arrays.sort()!而Arrays里面的sort

/*
* @param  list the list to be sorted.
* @throws ClassCastException if the list contains elements that are not
*         <i>mutually comparable</i> (for example, strings and integers).
* @throws UnsupportedOperationException if the specified list's
*         list-iterator does not support the {@code set} operation.
* @throws IllegalArgumentException (optional) if the implementation
*         detects that the natural ordering of the list elements is
*         found to violate the {@link Comparable} contract
*/
public static <T extends Comparable<? super T>> void sort(List<T> list) {
Object[] a = list.toArray();
Arrays.sort(a);
ListIterator<T> i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set((T)a[j]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: