//A tool class for operating collections, all of which are static methods. // sort according to the natural order of the elements public static <T extends Comparable<? super T>> void sort(List<T> list) { // Convert to array Object[] a = list.toArray(); //sort Arrays.sort(a); ListIterator<T> i = list.listIterator(); //Settings for (int j=0; j<a.length; j++) { i.next(); i.set((T)a[j]); } } // sort the elements according to the passed comparator public static <T> void sort(List<T> list, Comparator<? super T> c) { Object[] a = list.toArray(); Arrays.sort(a, (Comparator)c); ListIterator i = list.listIterator (); for (int j=0; j<a.length; j++) { i.next(); i.set(a[j]); } } //Use the binary search method to query the object according to the specified key public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c) { // no comparator passed in if (c==null) return binarySearch((List) list, key); if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD) return Collections.indexedBinarySearch(list, key, c); else return Collections.iteratorBinarySearch(list, key, c); } public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) { if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD) return Collections.indexedBinarySearch(list, key); else return Collections.iteratorBinarySearch(list, key); } private static <T> int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key) { int low = 0; int high = list.size()-1; while (low <= high) { int mid = (low + high) >>> 1; Comparable<? super T> midVal = list.get(mid); int cmp = midVal.compareTo(key); // look to the right if he is younger than him if (cmp < 0) low = mid + 1; // Look to the left if he is bigger than him else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } //Add the specified element to the collection public static <T> boolean addAll(Collection<? super T> c, T... elements) { boolean result = false; for (T element : elements) result |= c.add(element); return result; } //Return a deque view in the form of last in first out public static <T> Queue<T> asLifoQueue(Deque<T> deque) { return new AsLIFOQueue<>(deque); } //Returning a dynamic type-safe collection inserting the wrong type will throw a ClassCastException directly //The implementation is to add type checking when adding elements public static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> type) { return new CheckedCollection<>(c, type); } //Returning a dynamic type-safe list inserting the wrong type will throw a ClassCastException directly //The implementation is to add type checking when adding elements public static <E> List<E> checkedList(List<E> list, Class<E> type) { return (list instanceof RandomAccess ? new CheckedRandomAccessList<>(list, type) : new CheckedList<>(list, type)); } //Returning a dynamic type-safe map inserting the wrong type will directly throw a ClassCastException //The implementation is to add type checking when adding elements public static <K, V> Map<K, V> checkedMap(Map<K, V> m, Class<K> keyType, Class<V> valueType) { return new CheckedMap<>(m, keyType, valueType); } //Copy elements from one list to another public static <T> void copy(List<? super T> dest, List<? extends T> src) { int srcSize = src.size(); if (srcSize > dest.size()) throw new IndexOutOfBoundsException("Source does not fit in dest"); if (srcSize < COPY_THRESHOLD || (src instanceof RandomAccess && dest instanceof RandomAccess)) { for (int i=0; i<srcSize; i++) dest.set(i, src.get(i)); } else { ListIterator<? super T> di=dest.listIterator(); ListIterator<? extends T> si=src.listIterator(); for (int i=0; i<srcSize; i++) { di.next(); di.set(si.next()); } } } //return true if the two sets do not have the same element public static boolean disjoint(Collection<?> c1, Collection<?> c2) { Collection<?> contains = c2; Collection<?> iterate = c1; //This is more efficient as written in the comment if (c1 instanceof Set) { iterate = c2; contains = c1; } else if (!(c2 instanceof Set)) { int c1size = c1.size(); int c2size = c2.size(); if (c1size == 0 || c2size == 0) { return true; } //Large ones are more efficient if they contain small ones if (c1size > c2size) { iterate = c2; contains = c1; } } for (Object e : iterate) { if (contains.contains(e)) { // Found a common element. Collections are not disjoint. return false; } } return true; } //Replace all elements in the list with the specified element public static <T> void fill(List<? super T> list, T obj) { int size = list.size(); // Less than 25 or support random access if (size < FILL_THRESHOLD || list instanceof RandomAccess) { for (int i=0; i<size; i++) list.set(i, obj); } else { ListIterator<? super T> itr = list.listIterator(); for (int i=0; i<size; i++) { itr.next(); itr.set(obj); } } } //return the number of elements in the collection equal to public static int frequency(Collection<?> c, Object o) { int result = 0; if (o == null) { for (Object e : c) if (e == null) result++; } else { for (Object e : c) if (o.equals(e)) result++; } return result; } //Return the position where the source first appears in the target public static int indexOfSubList(List<?> source, List<?> target) { int sourceSize = source.size(); int targetSize = target.size(); //If the source list is shorter than the target list, return -1 directly int maxCandidate = sourceSize - targetSize; if (sourceSize < INDEXOFSUBLIST_THRESHOLD || (source instanceof RandomAccess&&target instanceof RandomAccess)) { nextCand: for (int candidate = 0; candidate <= maxCandidate; candidate++) { for (int i=0, j=candidate; i<targetSize; i++, j++) // if not equal then re-loop if (!eq(target.get(i), source.get(j))) continue nextCand; return candidate; } } else { // Iterator version of above algorithm ListIterator <?> Si = source.listIterator (); nextCand: for (int candidate = 0; candidate <= maxCandidate; candidate++) { ListIterator <?> Ti = target.listIterator (); for (int i=0; i<targetSize; i++) { if (!eq(ti.next(), si.next())) { // pointer to backtrack si for (int j=0; j<i; j++) si.previous(); continue nextCand; } } return candidate; } } return -1; // No candidate matched the target } //Return the last occurrence of target in source public static int lastIndexOfSubList(List<?> source, List<?> target) { int sourceSize = source.size(); int targetSize = target.size(); int maxCandidate = sourceSize - targetSize; if (sourceSize < INDEXOFSUBLIST_THRESHOLD || source instanceof RandomAccess) { // Index access version nextCand: for (int candidate = maxCandidate; candidate >= 0; candidate--) { for (int i=0, j=candidate; i<targetSize; i++, j++) if (!eq(target.get(i), source.get(j))) continue nextCand; // Element mismatch, try next cand return candidate; // All elements of candidate matched target } } else { // Iterator version of above algorithm if (maxCandidate < 0) return -1; ListIterator <?> Si = source.listIterator (maxCandidate); nextCand: for (int candidate = maxCandidate; candidate >= 0; candidate--) { ListIterator <?> Ti = target.listIterator (); for (int i=0; i<targetSize; i++) { if (!eq(ti.next(), si.next())) { if (candidate != 0) { // Back up source iterator to next candidate for (int j=0; j<=i+1; j++) si.previous(); } continue nextCand; } } return candidate; } } return -1; // No candidate matched the target } //return the maximum value according to the natural order of the elements public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) { Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (next.compareTo(candidate) > 0) candidate = next; } return candidate; } //Return the maximum value in the Collection according to the comparator comparison public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) { if (comp==null) return (T)max((Collection<SelfComparable>) (Collection) coll); Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (comp.compare(next, candidate) > 0) candidate = next; } return candidate; } //return the minimum value in the collection according to the natural order public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) { Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (next.compareTo(candidate) < 0) candidate = next; } return candidate; } //Return the minimum value in the Collection according to the comparator comparison public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) { if (comp==null) return (T)min((Collection<SelfComparable>) (Collection) coll); Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (comp.compare(next, candidate) < 0) candidate = next; } return candidate; } //return an immutable collection of n o's public static <T> List<T> nCopies(int n, T o) { if (n < 0) throw new IllegalArgumentException("List length = " + n); return new CopiesList<>(n, o); } //replace the old value public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) { boolean result = false; int size = list.size(); if (size < REPLACEALL_THRESHOLD || list instanceof RandomAccess) { if (oldVal==null) { for (int i=0; i<size; i++) { if (list.get(i)==null) { list.set(i, newVal); result = true; } } } else { for (int i=0; i<size; i++) { if (oldVal.equals(list.get(i))) { list.set(i, newVal); result = true; } } } } else { ListIterator<T> itr=list.listIterator(); if (oldVal==null) { for (int i=0; i<size; i++) { if (itr.next()==null) { itr.set(newVal); result = true; } } } else { for (int i=0; i<size; i++) { if (oldVal.equals(itr.next())) { itr.set(newVal); result = true; } } } } return result; } // reverse the entire list public static void reverse(List<?> list) { int size = list.size(); if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) { for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--) // swap the values of i and j positions swap(list, i, j); } else { ListIterator fwd = list.listIterator (); ListIterator rev = list.listIterator (size); for (int i=0, mid=list.size()>>1; i<mid; i++) { Object tmp = fwd.next(); fwd.set(rev.previous()); rev.set(tmp); } } } public static void swap(List<?> list, int i, int j) { final List l = list; l.set(i, l.set(j, l.get(i))); } // Randomly swap the position of list elements public static void shuffle(List<?> list) { Random rnd = r; if (rnd == null) r = rnd = new Random(); shuffle(list, rnd); } public static void shuffle(List<?> list, Random rnd) { int size = list.size(); if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) { for (int i=size; i>1; i--) swap(list, i-1, rnd.nextInt(i)); } else { Object arr[] = list.toArray(); // Shuffle array for (int i=size; i>1; i--) swap(arr, i-1, rnd.nextInt(i)); // Dump array back into list ListIterator it = list.listIterator (); for (int i=0; i<arr.length; i++) { it.next(); it.set(arr[i]); } } } //return a comparator that reverses the order public static <T> Comparator<T> reverseOrder() { return (Comparator<T>) ReverseComparator.REVERSE_ORDER; } // reverse the comparator order public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) { if (cmp == null) return reverseOrder(); if (cmp instanceof ReverseComparator2) return ((ReverseComparator2<T>)cmp).cmp; return new ReverseComparator2<>(cmp); } //Move the elements in the list by distance public static void rotate(List<?> list, int distance) { if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD) rotate1(list, distance); else rotate2(list, distance); } private static <T> void rotate1(List<T> list, int distance) { int size = list.size(); if (size == 0) return; distance = distance % size; if (distance < 0) distance += size; if (distance == 0) return; for (int cycleStart = 0, nMoved = 0; nMoved != size; cycleStart++) { T displaced = list.get(cycleStart); int i = cycleStart; do { i += distance; if (i >= size) i -= size; displaced = list.set(i, displaced); nMoved ++; } while (i != cycleStart); //return immutable set with only one element public static <T> Set<T> singleton(T o) { return new SingletonSet<>(o); } // Convert this collection to synchronous public static <T> Collection<T> synchronizedCollection(Collection<T> c) { return new SynchronizedCollection<>(c); } // Convert the collection to an immutable collection public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) { return new UnmodifiableCollection<>(c); }
Read Collections source code
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326378255&siteId=291194637
Recommended
Ranking