7.集合工具类

一.集合工具类-Arrays类

  1. Arrays类
    在Collection接口中有一个方法叫toArray把集合转换为Object数组.
把集合转换为数组: Object[] arr = 集合对象.toArray();

数组也可以转换为集合(List集合):

public static<T>List<T>asList(T...a)等价于public static<T>List<T>asList(T[] a)
//把数组转换为List对象
		//转换成长度固定的List
		List<String> list1 = Arrays.asList("A","B","C","D");
		List<Date> list2 = Arrays.asList(new Date());

通过Arrays.asList方法得到的List对象的长度是固定的,不能增,也不能减.
asList方法返回的ArrayList对象,不是java.util.ArrayList而是Arrays类中的内部类对象

新建类ArrayDemo

public class ArrayDemo {
	public static void main(String[] args) {
		//转换成长度固定的List
		List<String> list1 = Arrays.asList("A", "B", "C", "D");
		List<Date> list2 = Arrays.asList(new Date());
		System.out.println(list1);
		System.out.println(list2);
		//list1.remove(0);//运行报错UnsupportedOperationException
		list1.set(0, "x");//修改不会影响长度,不报错

		//这时候自动装箱
		List<Integer> listInteger = Arrays.asList(1, 2, 3, 4, 5);

		int[] i = { 1, 2, 3, 4, 5, 6 };
		//报错,此时不能自动装箱,把i看成一个整体
		//List<Integer> listInteger2 = Arrays.asList(i);
	}
}

二.集合工具类-Collections类

面试题:Collection和Collections的区别

Collection类:封装了Set,List,Map的操作的工具方法
获取空集对象(没有元素的集合,注意集合不为null)
	Collection list1 = Collections.EMPTY_LIST;//常量
	Collection list2 = Collections.emptyList();//方法
	Collection list3 = new ArrayList(); //从Java7开始,方法

常用的集合类:
HashSet/ArrayList/HashMap都是线程不安全的,在多线程环境下不安全.
在Collections类中获取线程安全集合的方法

List list = Collections.synchronizedList(new ArrayList());

当要做迭代的时候的使用synchronized

synchronized(list) {
      Iterator i = list.iterator(); // Must be in synchronized block
      while (i.hasNext())
          foo(i.next());
  }

Set set = Collections.synchronizedSet(new HashSet());

Map map = Collections.synchronizedMap(new HashMap());
static synchronizedCollection(Collection<T> c)  返回指定 collection 支持的同步(线程安全的)collection。
static synchronizedList(List<T> list)  返回指定列表支持的同步(线程安全的)列表。
static synchronizedMap(Map<K,V> m)  返回由指定映射支持的同步(线程安全的)映射。
static synchronizedSet(Set<T> s)  返回指定 set 支持的同步(线程安全的)set。
static synchronizedSortedMap(SortedMap<K,V> m)  返回指定有序映射支持的同步(线程安全的)有序映射。
static synchronizedSortedSet(SortedSet<T> s)  返回指定有序 set 支持的同步(线程安全的)有序 set。
发布了82 篇原创文章 · 获赞 0 · 访问量 1328

猜你喜欢

转载自blog.csdn.net/huang_kuh/article/details/105292179