Collections和Arrays常用方法
工具类Collections和Arrays
从名字上就很容易看出来,Collections是一个操作Collections集合的工具类,而Arrays是用来操作数组的工具类。
其中Arrays和Collections中所有的方法都为静态的,不需要创建对象,直接使用类名调用即可。
将list实现同步的方法:
1.使用vector.
2.Collections.synchronizedCollection();
3.使用同步块synchronized{}
将集合类变成线程安全的(synchronizedCollection(Collection c)、synchronizedList(List list)、synchronizedMap(Map<K,V> m)、synchronizedSet(Set s))方法。
主要学习里面的一些常用方法,Collections里的常用方法有:
//代码演示
import java.util.*;
class demo01
{
public static void main(String[] args)
{
ArrayList<String> arr = new ArrayList<String>();
arr.add("ddd");
arr.add("cd");
arr.add("asdfd");
arr.add("cd");
arr.add("asdh");
//没有排序
System.out.println("无序:"+arr);
//自然排序的方法
Collections.sort(arr);
System.out.println("自然排序"+arr);
//长度排序的方法
Collections.sort(arr,new arraylenghtCompare());
System.out.println("长度排序"+arr);
//用自己的方法
String max = Collections.max(arr,new arraylenghtCompare());
System.out.println("最长max="+max);
//自然排序的方法(用了自己定义的比较器)
Collections.sort(arr,new arrayCompare());
System.out.println("反自然排序"+arr);
//是在有序集合里找 如果没有找到就返回:(-(插入点)-1)
int indexd = Collections.binarySearch(arr,"cd");
System.out.println("cd:indexd="+indexd);;
//ddq替换ddd 按照元素替换
Collections.replaceAll(arr,"ddd","ddq");
Collections.reverse(arr);//反转元素
}
}
//自定义比较器:逆序排序
class arrayCompare implements Comparator<String>
{
public int compare(String s1,String s2)
{
return s2.compareTo(s1);
}
}
//自定义比较器:长度排序
class arraylenghtCompare implements Comparator<String>
{
public int compare(String s1,String s2)
{
return new Integer(s1.length()).compareTo(new Integer(s2.length()));
}
}
Arrays工具类中有对数组操作的方法:
//用一段小代码来演示
class demo03
{
public static void main(String[] args)
{
int[]ar = {3,4,5};
List<int[]> a = Arrays.asList(ar);//基本数据类型进行转换时 泛型就是这样
System.out.println(a);
Integer[]cc = {3,4,5};
List<Integer> c = Arrays.asList(cc);//引用数据类型进行转换时 泛型就直接
System.out.println(c);
ArrayList<String> arr = new ArrayList<String>();
arr.add("ddd");
arr.add("cd");
arr.add("asdfd");
arr.add("cd");
arr.add("asdh");
String []b = arr.toArray(new String[arr.size()]);
System.out.println(b.toString());
System.out.println("Hello World!");
}
}
数组和集合转换的好处:
将数组变成List集合可以用集合里面的方法(但是不能用增删的方法,因为数组的长度是固定的 否则会有异常),集合变数组可以限定对集合中元素的操作。