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)
List<String> nList=new ArrayList<String>(); nList.add("zhangsan"); nList.add("lisi"); nList.add("wangwu"); nList.add("zhaoliu"); nList.add("tianqi"); System.out.println("操作前"); for(String s:nList){ System.out.print(s+" "); } System.out.println(); System.out.println("交換順序後"); Collections.swap(nList,1,2); for(String s:nList){ System.out.print(s+" "); } System.out.println(); System.out.println("自然排序後"); Collections.sort(nList); for(String s:nList){ System.out.print(s+" "); } System.out.println(); System.out.println("二分法查找"); System.out.println(Collections.binarySearch(nList, "zhaoliu")); System.out.println("打亂順序"); Collections.shuffle(nList); for(String s:nList){ System.out.print(s+" "); } System.out.println(); System.out.println("填充"); Collections.fill(nList, "jay"); for(String s:nList){ System.out.print(s+" "); }
輸出結果:
操作前
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