JDK中提供的一个操作集合的工具:Collections,提供集对合对象的基本操作.
Collections.copy(List des,List src);
将src中的元素复制到des中,des必须比src大,并且不能为空,否则出错.des中比src中多的元素将保持不变.
static void sort(List elements)
static void sort(List elements, Comparator c)
Comparator 是一个排序器,可自定义的排序的方式(升,降)和比较值,如果不加此参数则按照升序(asc)对简单集合进行排序:Comparator.compare()对集合中相邻的两个元素进行比较,返回负数则升序,正数则降序.0则不交换.
[例子]
class SortObj {
int i;
String name;
public SortObj(int i, String name) {
this.i = i;
this.name = name;
}
}
public class SortCollection {
public static void main(String[] args) {
List list1 = new ArrayList();
list1.add(new SortObj(5, "name1"));
list1.add(new SortObj(3, "name3"));
list1.add(new SortObj(1, "name5"));
list1.add(new SortObj(4, "name2"));
list1.add(new SortObj(2, "name4"));
System.out.println("排序前: ");
for (int i = 0; i < list1.size(); i++) {
SortObj obj = (SortObj) list1.get(i);
System.out.println(obj.i + " " + obj.name);
}
Collections.sort(list1, new Comparator() {
public int compare(Object element1, Object element2) {
SortObj item1 = (SortObj) element1;
SortObj item2 = (SortObj) element2;
return item1.name.compareTo(item2.name);
}
});
System.out.println("排序后: ");
for (int i = 0; i < list1.size(); i++) {
SortObj obj = (SortObj) list1.get(i);
System.out.println(obj.i + " " + obj.name);
}
}
}
运行结果:
排序前:
5 name1
3 name3
1 name5
4 name2
2 name4
排序后:
5 name1
4 name2
3 name3
2 name4
1 name5
static Object min(Collection elements)
static Object max(Collection elements)
static Object min(Collection elements, Comparator c)
static Object max(Collection elements, Comparator c)
static void copy(List to, List from)
static void fill(List l, Object value)
static void replaceAll(List l,Object oldvalue, Object newvalue)
static int indexOfsubList(List l,List s)
static int lastingdexOfSubList(List l, List s)
static void reverse(List l)
static void rotate(List l, int d)
posted on 2005-08-22 23:42
ZhuJun 阅读(209)
评论(0) 编辑 收藏 所属分类:
开发手记