集合-Collections及常用方法

发布时间 2023-08-14 11:32:45作者: 苏汐sama

一. 概述

Collections类是Java提供的一个操作Set、List、Map等集合的工具类Collections 类提供了许多操作集合的静态方法,借助这些静态方法可以实现对集合元素的排序、查找替换和线程安全化等操作
Collections类中的方法都是静态的
Collections类中没有构造函数,不能进行实例化

二. 常用方法

1. 排序

 

/*1. 根据元素的自然顺序对指定List集合的元素按升序进行排序:
List集合中所有元素必须实现Comparable接口;
此方法只适用于List集合
*/
static <T extends Comparable<? super T>> void   sort(List<T> list);
/*2. 根据指定比较器的顺序对List集合元素进行排序:
此方法只适用于List集合
*/
/*
按照元素自然顺序排序
Collections.sort(list); 
按照字符串长度比较器进行排序
Collections.sort(list,new StrLenComparator());
*/
//字符串长度比较器
class StrLenComparator implements Comparator<String>{
  public int compare(String o1, String o2) {
    if(o1.length()>o2.length())
    return 1;
    if(o1.length()<o2.length())
    return -1;
    return o1.compareTo(o2);
  }
}
static <T> void   sort(List<T> list,Comparator<? super T> c);

 

 

 

2. 查找最值

 

/*1. 根据元素的自然顺序,返回集合中的最大元素:
集合中所有元素必须实现Comparable接口;
此方法只适用于Collection集合
*/
static <T exntends Object & Comparable<? super T>> T   max(Collection<? extends T> coll);
/*2. 根据指定比较器的顺序,返回集合中的最大元素:
此方法只适用于Collection集合
*/
static <T> T   max(Collection<? entends T> coll,Comparator<? super T> comp);
/*3. 根据元素的自然顺序,返回集合中的最小元素:
集合中所有元素必须实现Comparable接口;
此方法只适用于Collection集合
*/
static <T exntends Object & Comparable<? super T>> T   min(Collection<? extends T> coll);
/*4. 根据指定比较器的顺序,返回集合中的最小元素:
此方法只适用于Collection集合
*/
static <T> T   min(Collection<? entends T> coll,Comparator<? super T> comp);

//最大元素
String maxStr = Collections.max(list);
//最小元素
String minStr = Collections.min(list);

 

3. 二分搜索法

/*1. 使用二分搜索法搜索指定的List集合,以获得指定对象在List集合中的索引:
要使该方法可以正常工作,List集合中的元素要先按自然顺序升序排列;
此方法只适用于List集合
*/
static <T> int   binarySearch(List<? entends Comparable<? super T>> list,T key);
/*2. 使用二分搜索法搜索指定的List集合,以获得指定对象在List集合中的索引:
要使该方法可以正常工作,List集合中的元素要先按指定比较器进行升序排列;
此方法只适用于List集合
*/
 static <T> int   binarySearch(List<? extends T> list,T key,Comparator<? super T> c);


//注意一定要保证原集合有序呦 (*^▽^*)
Collections.sort(list);
//二分搜索集合list中str的位置下标,若不存在则返回一个小于0的数
int index1=Collections.binarySearch(list,str);
//集合list先按照自定义比较器进行排序后,再对str进行二分搜索
int index2=Collections.binarySearch(list,str,new StrLenComparator());