Collections工具类
Collections工具类介绍
- Collections 是一个操作Set、List 和 Map 等集合的工具类
- Collections 中提供了一系列静态的方法对集合元素进行排序、查询和修改等操作
Collections常用方法
排序操作:(均为static方法)
List list = new ArrayList();
list.add("tom");
list.add("smith");
list.add("king");
list.add("milan");
- reverse(List):反转 List 中元素的顺序
Collections.reverse(list);
System.out.println("list=" + list);
运行结果:list=[milan, king, smith, tom]
- shuffle(List):对 List 集合元素进行随机排序
Collections.shuffle(list);
System.out.println("list=" + list);
运行结果:list=[king, milan, tom, smith]
- sort(List):根据元素的自然顺序对指定 List 集合按升序排序
Collections.sort(list);
System.out.println("list=" + list);
运行结果:list=[king, milan, smith, tom]
- sort(List, Comparator):根据指定的 Comparator 产生的顺序对 List集合元素进行排序
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {//按字符串长度进行排序
//可加入校验代码
return ((String)o1).length() - ((String)o2).length();
}
});
System.out.println("list=" + list);
运行结果:list=[tom, king, smith, milan]
- swap(List, int, int):将指定 List 集合中的 i 处元素和 j 处元素进行交换
Collections.swap(list,0,1);
System.out.println("list=" + list);
运行结果:list=[smith, tom, king, milan]
查找、替换
- Object max(Collection):根据元素的自然排序,返回给定集合中最大元素
System.out.println(Collections.max(list));
运行结果:tom
- Object max(Collection, Comparator):根据 Comparator 指定的顺序返回给定集合中的最大元素
Object maxObject = Collections.max(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {//按字符串长度返回最大
return ((String) o1).length() - ((String) o2).length();
}
});
System.out.println(maxObject);
运行结果:smith
- Obeject min(Collection)
- Object min(Collection, Comparator)
参考max即可
- int frequency(Collection, Object):返回指定集合中指定元素出现的次数
略
- void copy(List dest, List src):将 src 中的内容复制到 dest 中
这里考虑三种方式
第一种,抛出 IndexOutOfBoundsException 异常
ArrayList dest = new ArrayList();
Collections.copy(dest,list);
System.out.println(dest);
第二种,指定一下初始大小,同样抛出 IndexOutOfBoundsException 异常
ArrayList dest = new ArrayList(list.size());
Collections.copy(dest,list);
System.out.println(dest);
第三种,先给dest 赋值,大小和 list.size() 一样,成功
ArrayList dest = new ArrayList();
for (int i = 0; i < list.size(); i++) {
dest.add("");
}
Collections.copy(dest,list);
System.out.println(dest);
运行结果:[tom, smith, king, milan]
- boolean replaceAll(List list, Object oldVal, Object newVal):使用新值替换 List 对象的所有旧值
略