---------------------- ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------
先区分一下Collection与Collections:
Collection:是一个接口,与其子类共同组成一个Collection集合框架
Collections:是一个类,一个服务于集合的工具类
集合框架的工具类
Collections
一 排序
Collections.sort(List list)
Collections.sort(List list , Comparator<? super T> c)
二 取最大值
Collections.max(Collection<? extends T> coll)
Collections.max(Collection<? extends T> coll , Comparator<? super T> comp);
三 折半查找
Collections.binarySearch(List<? extends Comparable<? super T>> , T key)
Collections binarySearch(List<? extends Comparable<? super T>> , T key , Comparator<? super T> c)
模拟折半查找
前提是要排一下序才能进行比较
例如:Collections.sort(list);
public static int halfSearch1(List<String> list , String key)
{
int min,mid,max;
min = 0;
max = list.size()-1;
while(min < max)
{
mid = (min+max)>>1;
String str = list.get(mid);
int num = str.comparaTo(key);
if(num > 0)
max = mid -1;
else if(num < 0)
min = mid +1;
else
return mid;
return -min-1;
}
}
//多加了个比较器
public static int halfSearch2(List<String> list , String key , Comparator<String> comp)
{
int min,mid,max;
min = 0;
max = list.size()-1;
while(min < max)
{
mid = (min+max)>>1;
String str = list.get(mid);
int num = comp.compare(str,key);
if(num > 0)
max = mid -1;
else if(num < 0)
min = mid +1;
else
return mid;
return -min-1;
}
}
class StrLenComparator implements Comparator<String>
{
public int compare(String s1 , String s2)
{
if(s1.length() > s2.length())
return 1;
if(s1.length() < s2.length())
return -1;
return s1.comparaTo(s2);
}
}
四 替换反转
Collections.fill(List<? extends T> list , T obj)
Collections.replace(List<? extends T> list , T oldVal , T newVal)
Collections.reverse(List<? extends T> list)
五 反转比较器
Collections.reverseOrder()
用法
new TreeSet<?>(Collections.reverseOrder())
其实就是可以当作一个比较器来用,与自然顺序相反
Collections.reverseOrder(Comparator<? super T> comp)
用法
new TreeSet<?>(Collections.reverseOrder(StrLenComparator))
将一个比较器放进反转比较器里可以改变规则,将定义的比较顺序反转
六 SynList线程安全
Collections.synchronizedList(List<T> list)
Collections.synchronizedSet(Set<T> set)
Collections.synchronizedMap(Map<K , V> map)
七 实用的其他方法
Collections.swap(List<?> list , int i , int j)//置换
Collections.shuffle(List<?> list)//扑克洗牌
Arrays
用于操作数组的工具类,里面都是静态方法
例如:Arrays.toString(int[] int);
asList:
将数组编程List集合
然后就可以使用集合的思想和方法操作数组中的元素
注意:将数组变成集合,不可以使用集合的增删方法,因为数组的长度是固定的
局限:只转换对象
如果数组中的元素都是对象,那么变成集合时,数组中的元素就直接转成集合中的元素
如果数组中的元素都是基本数据类型,那么会将该数组作为集合中的元素存在
---------------------- ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------详细请查看:www.itheima.com