常用方法的使用
public class Collections_ {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("tom");
list.add("jk");
list.add("gyc");
list.add("cjj");
list.add("simth");
System.out.println(list); //[tom, jk, gyc, cjj, simth]
//反转元素
Collections.reverse(list);
System.out.println(list); //[simth, cjj, gyc, jk, tom]
//将元素随机排序
Collections.shuffle(list);
System.out.println(list); //[jk, cjj, gyc, simth, tom]
//升序排序
Collections.sort(list);
System.out.println(list); //[cjj, gyc, jk, simth, tom]
//根据 Comparator 自定义的规则,对元素进行排序
// 比如,这里按照字符串长度排序
Collections.sort(list, new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
return (((String) o1).length()) - ((String) o2).length();
}
});
System.out.println(list); //[jk, cjj, gyc, tom, simth]
//交换两个位置的元素
Collections.swap(list,0,1);
System.out.println(list); //[cjj, jk, gyc, tom, simth]
//获取最大值
System.out.println(Collections.max(list)); //tom
//根据 Comparator 指定的顺序,返回给定集合中最大的元素
//例如,返回长度最大的元素
Object max = Collections.max(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return (((String) o1).length()) - ((String) o2).length();
}
});
System.out.println(max); //simth
//集合中元素出现的次数
System.out.println("tom出现了:"+Collections.frequency(list,"tom")); //tom出现了:1
//将list的内容复制到dest中
ArrayList dest = new ArrayList();
//为了完成一个完整的拷贝,我们需要先给dest赋值,大小和list.size()一样
for (int i = 0; i < list.size(); i++) {
dest.add("");
}
Collections.copy(dest,list);
System.out.println(dest); //[cjj, jk, gyc, tom, simth]
//使用新值替换集合中的旧值
//将list中的 tom 替换为 汤姆
Collections.replaceAll(list,"tom","汤姆");
System.out.println(list); //[cjj, jk, gyc, 汤姆, simth]
}
}