Java 集合工具类Collections总结
集合工具类(Collections) Collection与Collections区别:
Collection是单例集合的根接口 ,Collections是操作集合的一个工具类。 Collections工具类中的方法都是静态的。
Collections常用方法:
- 对list集合进行排序。
sort(list);
//对list进行排序,其实使用的事list容器中的对象的compareTo方法
sort(list,comaprator); - 对list进行二分查找: 前提该集合一定要有序。
int binarySearch(list,key);
//必须根据元素自然顺序对列表进行升级排序
//要求list 集合中的元素都是Comparable 的子类。
int binarySearch(list,key,Comparator); - 对集合取最大值或者最小值。
max(Collection)
max(Collection,comparator)
min(Collection)
min(Collection,comparator) - 对list集合进行反转。
reverse(list); - 可以将不同步的集合变成同步的集合。
Set synchronizedSet(Set s)
Map synchronizedMap(Mapm)
List synchronizedList(List list)
首先创建集合:
(1)创建有自然顺序的集合
ArrayList<Integer> list= new ArrayList<Integer>();
list.add(555);
list.add(999);
list.add(888);
list.add(222);
list.add(444);
list.add(123);
list.add(666);
list.add(333);
list.add(777);
(2)创建无自然顺序的集合
//如果存储的元素不具备自然顺序,那么排序需要传入比较器
ArrayList<Person> list = new ArrayList<Person>();
list.add(new Person("Ren", 15));
list.add(new Person("Hao", 56));
list.add(new Person("Ming", 22));
list.add(new Person("Juan", 29));
list.add(new Person("Liu", 33));
list.add(new Person("Guang", 7));
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "[ 姓名:"+name+" 年龄:"+age+" ]";
}
}
//比较器,对年龄进行比较
class AgeComparator implements Comparator<Person>{
public int compare(Person o1, Person o2) {
return o1.age-o2.age;
}
}
对list集合进行排序:
Collections.sort(list);
System.out.println("集合元素排序:"+list);
//如果存储的元素不具备自然顺序,那么排序需要传入比较器
Collections.sort(list, new AgeComparator());
System.out.println("集合中的元素按照年龄排序:"+list);
对集合进行二分查找,返回索引值(前提是有序):
System.out.println("元素所在的索引值:"+Collections.binarySearch(list,999));
System.out.println("集合所在的索引值:"+Collections.binarySearch(list, new Person("Ming", 22),new AgeComparator()));
求最大值和最小值:
System.out.println("最小值:"+Collections.min(list));
System.out.println("最大值:"+Collections.max(list));
System.out.println("按照年龄最小值:"+Collections.min(list,new AgeComparator()));
System.out.println("按照年龄最大值:"+Collections.max(list,new AgeComparator()));
对集合的反转
Collections.reverse(list);
System.out.println("反转后的顺序:"+list);
将集合转成线程安全:
list = (ArrayList<Integer>) Collections.synchronizedList(list);
还没有评论,来说两句吧...