你的位置:首页 > Java教程

[Java教程]Collection类及常用API


Collection类及常用API

Collection—类集工具类,定义了若干用于类集和映射的算法,这些算法被定义为静态方法,具体查看api文档;

a)  public static void sort(List<T> liet)

b)  public static int binarySearch(List<T> list,T key)

c)  public static void reverse(List<?> list)

d)  public static void shuffle(List<?> list)

e)  public static void swap(List<?> list,int i,int j)

f)   public static <T> void fill(List<? super T> list,T obj)

 1     List<String> nList=new ArrayList<String>(); 2     nList.add("zhangsan"); 3     nList.add("lisi"); 4     nList.add("wangwu"); 5     nList.add("zhaoliu"); 6     nList.add("tianqi"); 7     System.out.println("操作前"); 8     for(String s:nList){ 9       System.out.print(s+" ");10     }11     12     System.out.println();13     System.out.println("交换顺序后");14     Collections.swap(nList,1,2);15     for(String s:nList){16       System.out.print(s+" ");17     }18     19     System.out.println();20     System.out.println("自然排序后");21     Collections.sort(nList);22     for(String s:nList){23       System.out.print(s+" ");24     }25     26     System.out.println();27     System.out.println("二分法查找");28     System.out.println(Collections.binarySearch(nList, "zhaoliu"));29     30     System.out.println("打乱顺序");31     Collections.shuffle(nList);32     for(String s:nList){33       System.out.print(s+" ");34     }35     36     System.out.println();37     System.out.println("填充");38     Collections.fill(nList, "jay");39     for(String s:nList){40       System.out.print(s+" ");41     }

输出结果:

操作前

zhangsan lisi wangwu zhaoliu tianqi

交换顺序后

zhangsan wangwu lisi zhaoliu tianqi

自然排序后

lisi tianqi wangwu zhangsan zhaoliu

二分法查找

4

打乱顺序

zhaoliu tianqi wangwu zhangsan lisi

填充

jay jay jay jay jay