Java 集合工具类Collections总结

你的名字 2023-05-28 05:05 43阅读 0赞

集合工具类(Collections) Collection与Collections区别:
Collection是单例集合的根接口 ,Collections是操作集合的一个工具类。 Collections工具类中的方法都是静态的。
Collections常用方法:

  1. 对list集合进行排序。
    sort(list);
    //对list进行排序,其实使用的事list容器中的对象的compareTo方法
    sort(list,comaprator);
  2. 对list进行二分查找: 前提该集合一定要有序。
    int binarySearch(list,key);
    //必须根据元素自然顺序对列表进行升级排序
    //要求list 集合中的元素都是Comparable 的子类。
    int binarySearch(list,key,Comparator);
  3. 对集合取最大值或者最小值。
    max(Collection)
    max(Collection,comparator)
    min(Collection)
    min(Collection,comparator)
  4. 对list集合进行反转。
    reverse(list);
  5. 可以将不同步的集合变成同步的集合。
    Set synchronizedSet(Set s)
    Map synchronizedMap(Map m)
    List synchronizedList(List list)

首先创建集合:
(1)创建有自然顺序的集合

  1. ArrayList<Integer> list= new ArrayList<Integer>();
  2. list.add(555);
  3. list.add(999);
  4. list.add(888);
  5. list.add(222);
  6. list.add(444);
  7. list.add(123);
  8. list.add(666);
  9. list.add(333);
  10. list.add(777);

(2)创建无自然顺序的集合

  1. //如果存储的元素不具备自然顺序,那么排序需要传入比较器
  2. ArrayList<Person> list = new ArrayList<Person>();
  3. list.add(new Person("Ren", 15));
  4. list.add(new Person("Hao", 56));
  5. list.add(new Person("Ming", 22));
  6. list.add(new Person("Juan", 29));
  7. list.add(new Person("Liu", 33));
  8. list.add(new Person("Guang", 7));
  9. class Person {
  10. String name;
  11. int age;
  12. public Person(String name, int age) {
  13. this.name = name;
  14. this.age = age;
  15. }
  16. @Override
  17. public String toString() {
  18. // TODO Auto-generated method stub
  19. return "[ 姓名:"+name+" 年龄:"+age+" ]";
  20. }
  21. }
  22. //比较器,对年龄进行比较
  23. class AgeComparator implements Comparator<Person>{
  24. public int compare(Person o1, Person o2) {
  25. return o1.age-o2.age;
  26. }
  27. }

对list集合进行排序:

  1. Collections.sort(list);
  2. System.out.println("集合元素排序:"+list);
  3. //如果存储的元素不具备自然顺序,那么排序需要传入比较器
  4. Collections.sort(list, new AgeComparator());
  5. System.out.println("集合中的元素按照年龄排序:"+list);

对集合进行二分查找,返回索引值(前提是有序):

  1. System.out.println("元素所在的索引值:"+Collections.binarySearch(list,999));
  2. System.out.println("集合所在的索引值:"+Collections.binarySearch(list, new Person("Ming", 22),new AgeComparator()));

求最大值和最小值:

  1. System.out.println("最小值:"+Collections.min(list));
  2. System.out.println("最大值:"+Collections.max(list));
  3. System.out.println("按照年龄最小值:"+Collections.min(list,new AgeComparator()));
  4. System.out.println("按照年龄最大值:"+Collections.max(list,new AgeComparator()));

对集合的反转

  1. Collections.reverse(list);
  2. System.out.println("反转后的顺序:"+list);

将集合转成线程安全:

  1. list = (ArrayList<Integer>) Collections.synchronizedList(list);

发表评论

表情:
评论列表 (有 0 条评论,43人围观)

还没有评论,来说两句吧...

相关阅读