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

来源:互联网 发布:mac重启黑屏 编辑:程序博客网 时间:2024/05/23 20:54

操作集合的工具类: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
原创粉丝点击