集合工具类,里面都是静态方法
sort(List<T>) //数据类型必须实现comparable
sort(List<T>,Comparator<? super T>)
swap() //交换
binarySearch(List,"");
max(list)
max(list,Comparator<? super T>)
Collections.reverseOrder()
Collections.reverseOrder(Comparator<? super T>)
replaceAll(list,old,new)
fill(list,"cc") //全部替换
shuffle(list) //随机洗牌
List<String> list = new ArrayList<String>();
list.add("sfas");
list.add("agg");
list.add("rth");
list.add("xzbvz");
list.add("agg");
Collections.sort(list);
System.out.println(list); //[agg, agg, rth, sfas, xzbvz]
TreeSet<String> ts = new TreeSet<String>(Collections.reverseOrder());
ts.add("abc");
ts.add("bcd");
ts.add("cde");
ts.add("def");
System.out.println(ts);
给非同步的集合加锁
synchronizedCollection synchronizedMap synchronizedList
实现
List list = new ArrayList();
MyCollections.syncList(list); //变成同步的list
class MyCollections{
public static List syncList(List list){
return new MyList(list);
}
class MyList implements List{
private List list;
private static final Object lock = new Object();
MyList(List list){
this.list = list;
}
public boolean add(Object obj){
synchronized(lock){
return list.add(obj);
}
}
public boolean remove(Object obj){
synchronized(lock){
return list.remove(obj);
}
}
}
}
方法都是静态的
Arrays.toString()的实现
int[] iarr = {4,6,8,90,1,2,4};
System.out.println(myArraysToString(iarr)); //[4,6,8,90,1,2,4]
public static String myArraysToString(int[] a) {
int imax = a.length-1;
if(imax==-1) {
return "[]";
}
StringBuilder sb = new StringBuilder();
sb.append("[");
for(int i=0;;i++) { //避免了每次都判断
sb.append(a[i]);
if(i == imax) {
return sb.append("]").toString();
}
sb.append(',');
}
}
asList
int[] iarr = {4,6,8,90,1,2,4};
String[] arr = {"asdfas","agas","hh","sgas"};
List<String> list = Arrays.asList(arr);
List ilist = Arrays.asList(iarr);
System.out.println(list);
System.out.println(ilist);
//[asdfas, agas, hh, sgas]
//[[I@15db9742]
toArray
集合转成数组,可以对集合中元素操作的方法进行限定,不允许增删
List<String> list = new ArrayList<String>();
list.add("abc1");
list.add("abc2");
list.add("abc3");
//toArray需要传入一个指定数组,最好长度指定为集合长度,大于后面为null
String[] arr = list.toArray(new String[list.size()]);
System.out.println(Arrays.toString(arr)); //[abc1, abc2, abc3]1