集合操作的工具类:
1、Arrays类;
2、Collections类。
Arrays类:
在Collection接口中有一个方法叫toArray,把集合转换为Object数组。
把集合转换为数组:Object[] arr = 集合对象.toArray();
数组也可以转换为集合(List集合):
通过Arrays.asList方法得到的List对象的长度是固定的,不能增,也不能减。
为什么:asList方法返回的ArrayList对象不是java.util.ArrayList,而是Arrays类中的内部类对象。
面试题:Collection和Collections的区别:
Collections类封装了Set、List和Map的操作的工具方法,
获取空集对象(没有元素的集合,注意集合不为null)
List<Object> list1 = Collections.EMPTY_LIST;//常量
List<Object> list2 = Collections.emptyList();//方法
List<Object> list1 = new ArrayList<>();从java7开始,方法
常用的集合类:
HashSet、ArrayList和HashMap都是线程不安全的,在多线程环境下不安全。
在Collections类中有获取线程安全的集合方法:
List list = Collections.synchronizedList(new ArrayList());
当要做迭代的时候得使用synchronized。
synchronized(list){
//TODO
}
Set set = Collections.synchronizedSet(new HashSet());
1、Arrays类;
2、Collections类。
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<String> list = Arrays.asList("A","B","C","D");
List<Date> list = Arrays.asList(new Date(),new Date());通过Arrays.asList方法得到的List对象的长度是固定的,不能增,也不能减。
为什么:asList方法返回的ArrayList对象不是java.util.ArrayList,而是Arrays类中的内部类对象。
@SafeVarargs
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
/**
* @serial include
*/
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable
{
private static final long serialVersionUID = -2764017481108945198L;
private final E[] a;
ArrayList(E[] array) {
if (array==null)
throw new NullPointerException();
a = array;
}
public int size() {
return a.length;
}
public Object[] toArray() {
return a.clone();
}
public <T> T[] toArray(T[] a) {
int size = size();
if (a.length < size)
return Arrays.copyOf(this.a, size,
(Class<? extends T[]>) a.getClass());
System.arraycopy(this.a, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
public E get(int index) {
return a[index];
}
public E set(int index, E element) {
E oldValue = a[index];
a[index] = element;
return oldValue;
}
public int indexOf(Object o) {
if (o==null) {
for (int i=0; i<a.length; i++)
if (a[i]==null)
return i;
} else {
for (int i=0; i<a.length; i++)
if (o.equals(a[i]))
return i;
}
return -1;
}
public boolean contains(Object o) {
return indexOf(o) != -1;
}
}
面试题:Collection和Collections的区别:
Collections类封装了Set、List和Map的操作的工具方法,
获取空集对象(没有元素的集合,注意集合不为null)
List<Object> list1 = Collections.EMPTY_LIST;//常量
List<Object> list2 = Collections.emptyList();//方法
List<Object> list1 = new ArrayList<>();从java7开始,方法
常用的集合类:
HashSet、ArrayList和HashMap都是线程不安全的,在多线程环境下不安全。
在Collections类中有获取线程安全的集合方法:
List list = Collections.synchronizedList(new ArrayList());
当要做迭代的时候得使用synchronized。
synchronized(list){
//TODO
}
Set set = Collections.synchronizedSet(new HashSet());
Map map = Collections.synchronizedMap(new HashMap());
这个相对来说是比较少使用的,所以简单的说明一下。等有需要再去查看源码和API也是来得及。