简介

  • 上一篇我们学习了 Arrays的工具类,同样的,Collections 也是JDK提供的工具类。
  • 因为Collections是JDK官方提供的操作集合的工具类,所以很多部分都是重载方法,本篇只举例说明,因为使用的方法是一致的。本篇暂时不学习其内部过多的内部类

    1. public class Collections {
    2. private Collections() {
    3. }
    4. private static final int BINARYSEARCH_THRESHOLD = 5000;
    5. private static final int REVERSE_THRESHOLD = 18;
    6. private static final int SHUFFLE_THRESHOLD = 5;
    7. private static final int FILL_THRESHOLD = 25;
    8. private static final int ROTATE_THRESHOLD = 100;
    9. private static final int COPY_THRESHOLD = 10;
    10. private static final int REPLACEALL_THRESHOLD = 11;
    11. private static final int INDEXOFSUBLIST_THRESHOLD = 35;
    12. // 排序
    13. public static <T extends Comparable<? super T>> void sort(List<T> list) {
    14. list.sort(null);
    15. }
    16. // 二分查找
    17. public static <T>
    18. int binarySearch(List<? extends Comparable<? super T>> list, T key) {
    19. if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
    20. return Collections.indexedBinarySearch(list, key);
    21. else
    22. return Collections.iteratorBinarySearch(list, key);
    23. }
    24. // 二分查找辅助类
    25. private static <T>
    26. int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key) {
    27. int low = 0;
    28. int high = list.size()-1;
    29. while (low <= high) {
    30. int mid = (low + high) >>> 1;
    31. Comparable<? super T> midVal = list.get(mid);
    32. int cmp = midVal.compareTo(key);
    33. if (cmp < 0)
    34. low = mid + 1;
    35. else if (cmp > 0)
    36. high = mid - 1;
    37. else
    38. return mid; // key found
    39. }
    40. return -(low + 1); // key not found
    41. }
    42. private static <T>
    43. int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key)
    44. {
    45. int low = 0;
    46. int high = list.size()-1;
    47. ListIterator<? extends Comparable<? super T>> i = list.listIterator();
    48. while (low <= high) {
    49. int mid = (low + high) >>> 1;
    50. Comparable<? super T> midVal = get(i, mid);
    51. int cmp = midVal.compareTo(key);
    52. if (cmp < 0)
    53. low = mid + 1;
    54. else if (cmp > 0)
    55. high = mid - 1;
    56. else
    57. return mid; // key found
    58. }
    59. return -(low + 1); // key not found
    60. }
    61. // 获取第i个元素
    62. private static <T> T get(ListIterator<? extends T> i, int index) {
    63. T obj = null;
    64. int pos = i.nextIndex();
    65. if (pos <= index) {
    66. do {
    67. obj = i.next();
    68. } while (pos++ < index);
    69. } else {
    70. do {
    71. obj = i.previous();
    72. } while (--pos > index);
    73. }
    74. return obj;
    75. }
    76. // 反转指定列表中元素的顺序。
    77. // 此方法以线性时间运行。
    78. public static void reverse(List<?> list) {
    79. int size = list.size();
    80. if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
    81. for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
    82. swap(list, i, j);
    83. } else {
    84. // instead of using a raw type here, it's possible to capture
    85. // the wildcard but it will require a call to a supplementary
    86. // private method
    87. ListIterator fwd = list.listIterator();
    88. ListIterator rev = list.listIterator(size);
    89. for (int i=0, mid=list.size()>>1; i<mid; i++) {
    90. Object tmp = fwd.next();
    91. fwd.set(rev.previous());
    92. rev.set(tmp);
    93. }
    94. }
    95. }
    96. // 随机的置换使用随机的默认源指定列表 随机置换列表
    97. public static void shuffle(List<?> list) {
    98. Random rnd = r;
    99. if (rnd == null)
    100. r = rnd = new Random(); // harmless race.
    101. shuffle(list, rnd);
    102. }
    103. // 随机对象
    104. private static Random r;
    105. // 元素互换操作
    106. public static void swap(List<?> list, int i, int j) {
    107. final List l = list;
    108. l.set(i, l.set(j, l.get(i)));
    109. }
    110. private static void swap(Object[] arr, int i, int j) {
    111. Object tmp = arr[i];
    112. arr[i] = arr[j];
    113. arr[j] = tmp;
    114. }
    115. // 替换所有指定列表与指定元素的元素。
    116. public static <T> void fill(List<? super T> list, T obj) {
    117. int size = list.size();
    118. if (size < FILL_THRESHOLD || list instanceof RandomAccess) {
    119. for (int i=0; i<size; i++)
    120. list.set(i, obj);
    121. } else {
    122. ListIterator<? super T> itr = list.listIterator();
    123. for (int i=0; i<size; i++) {
    124. itr.next();
    125. itr.set(obj);
    126. }
    127. }
    128. }
    129. // 将所有从一个列表中的元素到另一个的
    130. public static <T> void copy(List<? super T> dest, List<? extends T> src) {
    131. int srcSize = src.size();
    132. if (srcSize > dest.size())
    133. throw new IndexOutOfBoundsException("Source does not fit in dest");
    134. if (srcSize < COPY_THRESHOLD ||
    135. (src instanceof RandomAccess && dest instanceof RandomAccess)) {
    136. for (int i=0; i<srcSize; i++)
    137. dest.set(i, src.get(i));
    138. } else {
    139. ListIterator<? super T> di=dest.listIterator();
    140. ListIterator<? extends T> si=src.listIterator();
    141. for (int i=0; i<srcSize; i++) {
    142. di.next();
    143. di.set(si.next());
    144. }
    145. }
    146. }
    147. // 返回集合中的最小元素
    148. public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
    149. Iterator<? extends T> i = coll.iterator();
    150. T candidate = i.next();
    151. while (i.hasNext()) {
    152. T next = i.next();
    153. if (next.compareTo(candidate) < 0)
    154. candidate = next;
    155. }
    156. return candidate;
    157. }
    158. // 返回集合自然排序最大的元素
    159. public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
    160. Iterator<? extends T> i = coll.iterator();
    161. T candidate = i.next();
    162. while (i.hasNext()) {
    163. T next = i.next();
    164. if (next.compareTo(candidate) > 0)
    165. candidate = next;
    166. }
    167. return candidate;
    168. }
    169. // 旋转在指定列表中的元素由所述指定的距离
    170. public static void rotate(List<?> list, int distance) {
    171. if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD)
    172. rotate1(list, distance);
    173. else
    174. rotate2(list, distance);
    175. }
    176. private static <T> void rotate1(List<T> list, int distance) {
    177. int size = list.size();
    178. if (size == 0)
    179. return;
    180. distance = distance % size;
    181. if (distance < 0)
    182. distance += size;
    183. if (distance == 0)
    184. return;
    185. for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) {
    186. T displaced = list.get(cycleStart);
    187. int i = cycleStart;
    188. do {
    189. i += distance;
    190. if (i >= size)
    191. i -= size;
    192. displaced = list.set(i, displaced);
    193. nMoved ++;
    194. } while (i != cycleStart);
    195. }
    196. }
    197. private static void rotate2(List<?> list, int distance) {
    198. int size = list.size();
    199. if (size == 0)
    200. return;
    201. int mid = -distance % size;
    202. if (mid < 0)
    203. mid += size;
    204. if (mid == 0)
    205. return;
    206. reverse(list.subList(0, mid));
    207. reverse(list.subList(mid, size));
    208. reverse(list);
    209. }
    210. // 替换
    211. public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) {
    212. boolean result = false;
    213. int size = list.size();
    214. if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) {
    215. if (oldVal==null) {
    216. for (int i=0; i<size; i++) {
    217. if (list.get(i)==null) {
    218. list.set(i, newVal);
    219. result = true;
    220. }
    221. }
    222. } else {
    223. for (int i=0; i<size; i++) {
    224. if (oldVal.equals(list.get(i))) {
    225. list.set(i, newVal);
    226. result = true;
    227. }
    228. }
    229. }
    230. } else {
    231. ListIterator<T> itr=list.listIterator();
    232. if (oldVal==null) {
    233. for (int i=0; i<size; i++) {
    234. if (itr.next()==null) {
    235. itr.set(newVal);
    236. result = true;
    237. }
    238. }
    239. } else {
    240. for (int i=0; i<size; i++) {
    241. if (oldVal.equals(itr.next())) {
    242. itr.set(newVal);
    243. result = true;
    244. }
    245. }
    246. }
    247. }
    248. return result;
    249. }
    250. // 返回指定目标列表中第一次出现的指定源列表中的起始位置,或-1
    251. public static int indexOfSubList(List<?> source, List<?> target) {
    252. int sourceSize = source.size();
    253. int targetSize = target.size();
    254. int maxCandidate = sourceSize - targetSize;
    255. if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
    256. (source instanceof RandomAccess&&target instanceof RandomAccess)) {
    257. nextCand:
    258. for (int candidate = 0; candidate <= maxCandidate; candidate++) {
    259. for (int i=0, j=candidate; i<targetSize; i++, j++)
    260. if (!eq(target.get(i), source.get(j)))
    261. continue nextCand; // Element mismatch, try next cand
    262. return candidate; // All elements of candidate matched target
    263. }
    264. } else { // Iterator version of above algorithm
    265. ListIterator<?> si = source.listIterator();
    266. nextCand:
    267. for (int candidate = 0; candidate <= maxCandidate; candidate++) {
    268. ListIterator<?> ti = target.listIterator();
    269. for (int i=0; i<targetSize; i++) {
    270. if (!eq(ti.next(), si.next())) {
    271. // Back up source iterator to next candidate
    272. for (int j=0; j<i; j++)
    273. si.previous();
    274. continue nextCand;
    275. }
    276. }
    277. return candidate;
    278. }
    279. }
    280. return -1; // No candidate matched the target
    281. }
    282. // 返回指定目标列表中最后一次出现的指定源列表中的起始位置,或-1
    283. public static int lastIndexOfSubList(List<?> source, List<?> target) {
    284. int sourceSize = source.size();
    285. int targetSize = target.size();
    286. int maxCandidate = sourceSize - targetSize;
    287. if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
    288. source instanceof RandomAccess) { // Index access version
    289. nextCand:
    290. for (int candidate = maxCandidate; candidate >= 0; candidate--) {
    291. for (int i=0, j=candidate; i<targetSize; i++, j++)
    292. if (!eq(target.get(i), source.get(j)))
    293. continue nextCand; // Element mismatch, try next cand
    294. return candidate; // All elements of candidate matched target
    295. }
    296. } else { // Iterator version of above algorithm
    297. if (maxCandidate < 0)
    298. return -1;
    299. ListIterator<?> si = source.listIterator(maxCandidate);
    300. nextCand:
    301. for (int candidate = maxCandidate; candidate >= 0; candidate--) {
    302. ListIterator<?> ti = target.listIterator();
    303. for (int i=0; i<targetSize; i++) {
    304. if (!eq(ti.next(), si.next())) {
    305. if (candidate != 0) {
    306. // Back up source iterator to next candidate
    307. for (int j=0; j<=i+1; j++)
    308. si.previous();
    309. }
    310. continue nextCand;
    311. }
    312. }
    313. return candidate;
    314. }
    315. }
    316. return -1; // No candidate matched the target
    317. }
    318. // 内部类 SynchronizedCollection 实现了Collection接口 内部的方法使用 关键字 synchronized修饰,是线程安全的
    319. static class SynchronizedCollection<E> implements Collection<E>, Serializable {
    320. private static final long serialVersionUID = 3053995032091335093L;
    321. final Collection<E> c; // Backing Collection
    322. final Object mutex; // Object on which to synchronize
    323. SynchronizedCollection(Collection<E> c) {
    324. this.c = Objects.requireNonNull(c);
    325. mutex = this;
    326. }
    327. SynchronizedCollection(Collection<E> c, Object mutex) {
    328. this.c = Objects.requireNonNull(c);
    329. this.mutex = Objects.requireNonNull(mutex);
    330. }
    331. public int size() {
    332. synchronized (mutex) {return c.size();}
    333. }
    334. public boolean isEmpty() {
    335. synchronized (mutex) {return c.isEmpty();}
    336. }
    337. public boolean contains(Object o) {
    338. synchronized (mutex) {return c.contains(o);}
    339. }
    340. public Object[] toArray() {
    341. synchronized (mutex) {return c.toArray();}
    342. }
    343. public <T> T[] toArray(T[] a) {
    344. synchronized (mutex) {return c.toArray(a);}
    345. }
    346. public Iterator<E> iterator() {
    347. return c.iterator(); // Must be manually synched by user!
    348. }
    349. public boolean add(E e) {
    350. synchronized (mutex) {return c.add(e);}
    351. }
    352. public boolean remove(Object o) {
    353. synchronized (mutex) {return c.remove(o);}
    354. }
    355. public boolean containsAll(Collection<?> coll) {
    356. synchronized (mutex) {return c.containsAll(coll);}
    357. }
    358. public boolean addAll(Collection<? extends E> coll) {
    359. synchronized (mutex) {return c.addAll(coll);}
    360. }
    361. public boolean removeAll(Collection<?> coll) {
    362. synchronized (mutex) {return c.removeAll(coll);}
    363. }
    364. public boolean retainAll(Collection<?> coll) {
    365. synchronized (mutex) {return c.retainAll(coll);}
    366. }
    367. public void clear() {
    368. synchronized (mutex) {c.clear();}
    369. }
    370. public String toString() {
    371. synchronized (mutex) {return c.toString();}
    372. }
    373. // Override default methods in Collection
    374. @Override
    375. public void forEach(Consumer<? super E> consumer) {
    376. synchronized (mutex) {c.forEach(consumer);}
    377. }
    378. @Override
    379. public boolean removeIf(Predicate<? super E> filter) {
    380. synchronized (mutex) {return c.removeIf(filter);}
    381. }
    382. @Override
    383. public Spliterator<E> spliterator() {
    384. return c.spliterator(); // Must be manually synched by user!
    385. }
    386. @Override
    387. public Stream<E> stream() {
    388. return c.stream(); // Must be manually synched by user!
    389. }
    390. @Override
    391. public Stream<E> parallelStream() {
    392. return c.parallelStream(); // Must be manually synched by user!
    393. }
    394. private void writeObject(ObjectOutputStream s) throws IOException {
    395. synchronized (mutex) {s.defaultWriteObject();}
    396. }
    397. }
    398. // 再来看一个
    399. // SynchronizedSet 也是线程安全的
    400. static class SynchronizedSortedSet<E>
    401. extends SynchronizedSet<E>
    402. implements SortedSet<E>
    403. {
    404. private static final long serialVersionUID = 8695801310862127406L;
    405. private final SortedSet<E> ss;
    406. SynchronizedSortedSet(SortedSet<E> s) {
    407. super(s);
    408. ss = s;
    409. }
    410. SynchronizedSortedSet(SortedSet<E> s, Object mutex) {
    411. super(s, mutex);
    412. ss = s;
    413. }
    414. public Comparator<? super E> comparator() {
    415. synchronized (mutex) {return ss.comparator();}
    416. }
    417. public SortedSet<E> subSet(E fromElement, E toElement) {
    418. synchronized (mutex) {
    419. return new SynchronizedSortedSet<>(
    420. ss.subSet(fromElement, toElement), mutex);
    421. }
    422. }
    423. public SortedSet<E> headSet(E toElement) {
    424. synchronized (mutex) {
    425. return new SynchronizedSortedSet<>(ss.headSet(toElement), mutex);
    426. }
    427. }
    428. public SortedSet<E> tailSet(E fromElement) {
    429. synchronized (mutex) {
    430. return new SynchronizedSortedSet<>(ss.tailSet(fromElement),mutex);
    431. }
    432. }
    433. public E first() {
    434. synchronized (mutex) {return ss.first();}
    435. }
    436. public E last() {
    437. synchronized (mutex) {return ss.last();}
    438. }
    439. }
    440. // SynchronizedList 也是内部通过 synchronized 实现线程安全
    441. static class SynchronizedRandomAccessList<E>
    442. extends SynchronizedList<E>
    443. implements RandomAccess {
    444. SynchronizedRandomAccessList(List<E> list) {
    445. super(list);
    446. }
    447. SynchronizedRandomAccessList(List<E> list, Object mutex) {
    448. super(list, mutex);
    449. }
    450. public List<E> subList(int fromIndex, int toIndex) {
    451. synchronized (mutex) {
    452. return new SynchronizedRandomAccessList<>(
    453. list.subList(fromIndex, toIndex), mutex);
    454. }
    455. }
    456. private static final long serialVersionUID = 1530674583602358482L;
    457. /**
    458. * Allows instances to be deserialized in pre-1.4 JREs (which do
    459. * not have SynchronizedRandomAccessList). SynchronizedList has
    460. * a readResolve method that inverts this transformation upon
    461. * deserialization.
    462. */
    463. private Object writeReplace() {
    464. return new SynchronizedList<>(list);
    465. }
    466. }
    467. // 其他的也是一样的原理 此处不在赘述
    468. // 下面再看几个方法
    469. // 获取 SynchronizedCollection对象
    470. public static <T> Collection<T> synchronizedCollection(Collection<T> c) {
    471. return new SynchronizedCollection<>(c);
    472. }
    473. // 返回线程安全的list
    474. public static <T> List<T> synchronizedList(List<T> list) {
    475. return (list instanceof RandomAccess ?
    476. new SynchronizedRandomAccessList<>(list) :
    477. new SynchronizedList<>(list));
    478. }
    479. // 返回线程安全的Map
    480. public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
    481. return new SynchronizedMap<>(m);
    482. }
    483. // 其他的也是一样的原理 此处不在赘述
    484. // 返回一个 空List
    485. public static final <T> List<T> emptyList() {
    486. return (List<T>) EMPTY_LIST;
    487. }
    488. public static final List EMPTY_LIST = new EmptyList<>();
    489. private static class EmptyList<E>
    490. extends AbstractList<E>
    491. implements RandomAccess, Serializable {
    492. private static final long serialVersionUID = 8842843931221139166L;
    493. public Iterator<E> iterator() {
    494. return emptyIterator();
    495. }
    496. public ListIterator<E> listIterator() {
    497. return emptyListIterator();
    498. }
    499. public int size() {return 0;}
    500. public boolean isEmpty() {return true;}
    501. public boolean contains(Object obj) {return false;}
    502. public boolean containsAll(Collection<?> c) { return c.isEmpty(); }
    503. public Object[] toArray() { return new Object[0]; }
    504. public <T> T[] toArray(T[] a) {
    505. if (a.length > 0)
    506. a[0] = null;
    507. return a;
    508. }
    509. public E get(int index) {
    510. throw new IndexOutOfBoundsException("Index: "+index);
    511. }
    512. public boolean equals(Object o) {
    513. return (o instanceof List) && ((List<?>)o).isEmpty();
    514. }
    515. public int hashCode() { return 1; }
    516. @Override
    517. public boolean removeIf(Predicate<? super E> filter) {
    518. Objects.requireNonNull(filter);
    519. return false;
    520. }
    521. @Override
    522. public void replaceAll(UnaryOperator<E> operator) {
    523. Objects.requireNonNull(operator);
    524. }
    525. @Override
    526. public void sort(Comparator<? super E> c) {
    527. }
    528. // Override default methods in Collection
    529. @Override
    530. public void forEach(Consumer<? super E> action) {
    531. Objects.requireNonNull(action);
    532. }
    533. @Override
    534. public Spliterator<E> spliterator() { return Spliterators.emptySpliterator(); }
    535. // Preserves singleton property
    536. private Object readResolve() {
    537. return EMPTY_LIST;
    538. }
    539. }
    540. // 其他方法类似于此
    541. // 返回指定列表的一个动态类型安全视图
    542. public static <E> List<E> checkedList(List<E> list, Class<E> type) {
    543. return (list instanceof RandomAccess ?
    544. new CheckedRandomAccessList<>(list, type) :
    545. new CheckedList<>(list, type));
    546. }
    547. // 其他方法类似于此
    548. }

    总结

  • 从源码我们可以看出来,Collections 类提供了很多操作集合的方法

  • 尤其是在Java集合框架中不是线程安全的如HashSet、HashMap、ArratList、LinkedList等
  • 但是也可以使用JUC下的线程安全的集合框架