操作集合的工具类:Collections使用示例

操作集合的工具类:Collections

提供包括元素的排序、查询、修改等操作,还实现将集合对象设置为不可变类,对集合对象实现同步控制等

使用实例1:普通操作
import java.util.ArrayList;
import java.util.Collections;

public class TestCol {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  ArrayList al = new ArrayList();
  al.add(2);
  al.add(-5);
  al.add(3);
  al.add(0);
  System.out.println(al);
  //输出最大、最小值
  System.out.println(Collections.max(al));
  System.out.println(Collections.min(al));
  //替换
  Collections.replaceAll(al, 0, 1);
  System.out.println(al);
  //判断-5在集合中出现的次数
  System.out.println(Collections.frequency(al, -5));
  //排序
  Collections.sort(al);
  System.out.println(al);
  //二分查找
  System.out.println(Collections.binarySearch(al, -5));

 }

}

实例2:同步控制

public class TestSynchronized {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Collection c = Collections.synchronizedCollection(new ArrayList());
  List l = Collections.synchronizedList(new ArrayList());
  Set s = Collections.synchronizedSet(new HashSet());
  Map m = Collections.synchronizedMap(new HashMap());

 }

}

实例3:设置不可变类

public class TestUnmodifiable {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  List ul = Collections.emptyList();
  
  Set us = Collections.singleton("this is a Set");
  
  Map m = new HashMap();
  
  m.put("语文", 80);
  m.put("数学", 60);
  
  Map um = Collections.unmodifiableMap(m);
  
    //以下代码引发异常
    ul.add("hello");
    us.add("hello");
    um.put("语文", 90);
  
  
 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值