Java 集合工具类Collections总结

集合工具类(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<K,V> m)
    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);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值