Collections 和 Objects 的使用注意
Collections 的使用注意
Collections 有和 Arrays 一样的排序方法 sort(),也有查找方法,比如 binarySearch(),Collections 的排序底层方法其实也是用的 Arrays.sort(),binarySearch 是自己重写的二分查找,但是其逻辑和 Arrays 的二分查找是一致的。
求集合中最大、小值:
Collections 提供了 max 方法来取得集合中的最大值,min 方法来取得集合中的最小值。
max 和 min 都提供了两种类型的方法,一个需要传外部排序器,一个不需要传排序器,但需要集合中的元素强制实现 Comparable 接口。
线程安全的集合
Collections 中线程安全的集合方法命名都是 synchronized 开始的,例如:
Collections.synchronizedCollection()
Collections.synchronizedList()
Collections.synchronizedMap()
Collections.synchronizedSet()
......
底层是通过 synchronized 轻量锁来实现的。
例如:
static class SynchronizedList<E> extends SynchronizedCollection<E> implements List<E> { private static final long serialVersionUID = -7754090372962971524L;
......
SynchronizedList(List<E> list, Object mutex) { super(list, mutex); this.list = list; }
......
public E get(int index) { synchronized (mutex) { return list.get(index); } }
public E set(int index, E element) { synchronized (mutex) { return list.set(index, element); } }
......
public E remove(int index) { synchronized (mutex) { return list.remove(index); } }
......
public boolean addAll(int index, Collection<? extends E> c) { synchronized (mutex) { return list.addAll(index, c); } }}
复制代码
不可变的集合
获得不可变集合的方法都是以 unmodifiable 开头的。这类方法会从原集合中,得到一个不可变的新集合,新集合只能访问,无法修改;一旦修改,就会抛出异常。主要是因为新集合内部只开放了查询方法,其余任何修改操作都会抛出异常。
例如:
static class UnmodifiableList<E> extends UnmodifiableCollection<E> implements List<E> { private static final long serialVersionUID = -283967356065247728L;
final List<? extends E> list;
UnmodifiableList(List<? extends E> list) { super(list); this.list = list; }
......
public E get(int index) { return list.get(index); } public E set(int index, E element) { throw new UnsupportedOperationException(); } ......}
复制代码
Objects 的使用注意
相等判断
Objects 提供了两种方法进行相等判断,一个是判断基本类型和自定义类的,另一个是用来判断数组的,分别是 equals() 和 deepEquals()。
源码:
public static boolean equals(Object a, Object b) { return (a == b) || (a != null && a.equals(b)); }
public static boolean deepEquals(Object a, Object b) { if (a == b) return true; else if (a == null || b == null) return false; else return Arrays.deepEquals0(a, b); }
复制代码
空判断
Objects 提供一些关于空值的判断,其中,isNull() 和 nonNull() 判断对象是否为空,返回 boolean 值。requireNonNull() 方法是校验参数一旦为空,就会直接抛出异常。
评论