Collections
Common methods of Collections tool class:
- sort
- Find, replace operation
- Synchronization control (not recommended, consider using concurrent collections under the JUC package when thread safe collection types are required)
Sort operation
void reverse(List list)//Reversal void shuffle(List list)//Stochastic ranking void sort(List list)//Ascending sort by natural sort void sort(List list, Comparator c)//Custom sorting, with the sorting logic controlled by the Comparator void swap(List list, int i , int j)//Exchange elements at two index locations void rotate(List list, int distance)//Rotation. When the distance is a positive number, move the distance elements after the list to the front as a whole. When the distance is negative, move the first distance elements of the list to the back as a whole.
Example code:
ArrayList<Integer> arrayList = new ArrayList<Integer>(); arrayList.add(-1); arrayList.add(3); arrayList.add(3); arrayList.add(-5); arrayList.add(7); arrayList.add(4); arrayList.add(-9); arrayList.add(-7); System.out.println("Primitive array:"); System.out.println(arrayList); // void reverse(List list): reverse Collections.reverse(arrayList); System.out.println("Collections.reverse(arrayList):"); System.out.println(arrayList); Collections.rotate(arrayList, 4); System.out.println("Collections.rotate(arrayList, 4):"); System.out.println(arrayList); // void sort(List list), in ascending order of natural sort Collections.sort(arrayList); System.out.println("Collections.sort(arrayList):"); System.out.println(arrayList); // void shuffle(List list), random sort Collections.shuffle(arrayList); System.out.println("Collections.shuffle(arrayList):"); System.out.println(arrayList); // Custom sort usage Collections.sort(arrayList, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2.compareTo(o1); } }); System.out.println("After custom sorting:"); System.out.println(arrayList);
Find, replace operation
int binarySearch(List list, Object key)//Binary search the List and return the index. Note that the List must be ordered int max(Collection coll)//Returns the largest element according to its natural order. Analogy int min (collection Col) int max(Collection coll, Comparator c)//According to the custom sorting, the maximum element is returned, and the sorting rules are controlled by the comparator class. Analogy int min (collection col, comparator C) void fill(List list, Object obj)//Replaces all elements in the specified list with the specified elements. int frequency(Collection c, Object o)//Count element occurrences int indexOfSubList(List list, List target)//Count the index of the first time that the start appears in the list, and return - 1 if it cannot be found. The analogy is int lastindexofsublist (list source, list targe t) boolean replaceAll(List list, Object oldVal, Object newVal), Replace old elements with new ones
Example code:
ArrayList<Integer> arrayList = new ArrayList<Integer>(); arrayList.add(-1); arrayList.add(3); arrayList.add(3); arrayList.add(-5); arrayList.add(7); arrayList.add(4); arrayList.add(-9); arrayList.add(-7); ArrayList<Integer> arrayList2 = new ArrayList<Integer>(); arrayList2.add(-3); arrayList2.add(-5); arrayList2.add(7); System.out.println("Primitive array:"); System.out.println(arrayList); System.out.println("Collections.max(arrayList):"); System.out.println(Collections.max(arrayList)); System.out.println("Collections.min(arrayList):"); System.out.println(Collections.min(arrayList)); System.out.println("Collections.replaceAll(arrayList, 3, -3):"); Collections.replaceAll(arrayList, 3, -3); System.out.println(arrayList); System.out.println("Collections.frequency(arrayList, -3):"); System.out.println(Collections.frequency(arrayList, -3)); System.out.println("Collections.indexOfSubList(arrayList, arrayList2):"); System.out.println(Collections.indexOfSubList(arrayList, arrayList2)); System.out.println("Collections.binarySearch(arrayList, 7):"); // Binary search of List, return index, List must be in order Collections.sort(arrayList); System.out.println(Collections.binarySearch(arrayList, 7));
Synchronous control
Collectionons provides multiple methods of synchronizedXxx(), which can wrap the specified collection into a collection of thread synchronization, so as to solve the thread safety problem when multiple threads access the collection concurrently.
We know that HashSet, TreeSet, ArrayList, LinkedList, HashMap and treemap are all thread unsafe. Collections provides multiple static methods to wrap them into thread synchronized collections.
It is better not to use the following methods, which are very inefficient. When you need thread safe collection types, consider using concurrent collections under the JUC package.
The method is as follows:
synchronizedCollection(Collection<T> c) //Returns the synchronous (thread safe) collection supported by the specified collection. synchronizedList(List<T> list)//Returns the List of synchronization (thread safe) supported by the specified List. synchronizedMap(Map<K,V> m) //Returns a synchronized (thread safe) Map supported by the specified Map. synchronizedSet(Set<T> s) //Returns the set of synchronization (thread safe) supported by the specified set.
Common operations of Arrays class
- Sort:? sort()
- Find: binarySearch()
- Compare: equals()
- Fill:? fill()
- Transfer list: asList()
- To string:'toString()
Sort:? sort()
// *************sort**************** int a[] = { 1, 3, 2, 7, 6, 5, 4, 9 }; // sort(int[] a) method sorts the specified array in numerical order. Arrays.sort(a); System.out.println("Arrays.sort(a):"); for (int i : a) { System.out.print(i); } // Line feed System.out.println(); // sort(int[] a,int fromIndex,int toIndex) sorts the specified range of an array in ascending order int b[] = { 1, 3, 2, 7, 6, 5, 4, 9 }; Arrays.sort(b, 2, 6); System.out.println("Arrays.sort(b, 2, 6):"); for (int i : b) { System.out.print(i); } // Line feed System.out.println(); int c[] = { 1, 3, 2, 7, 6, 5, 4, 9 }; // parallelSort(int[] a) sorts the specified array in numerical order. As with sort method, there is sorting by range Arrays.parallelSort(c); System.out.println("Arrays.parallelSort(c): "); for (int i : c) { System.out.print(i); } // Line feed System.out.println(); // parallelSort sorts character arrays. sort can also char d[] = { 'a', 'f', 'b', 'c', 'e', 'A', 'C', 'B' }; Arrays.parallelSort(d); System.out.println("Arrays.parallelSort(d): "); for (char d2 : d) { System.out.print(d2); } // Line feed System.out.println();
When we do algorithm interview questions, we may often encounter the situation of sorting strings. Arrays.sort(), compares the specific positions of each string, and then sorts them in ascending order.
String[] strs = { "abcdehg", "abcdefg", "abcdeag" }; Arrays.sort(strs); System.out.println(Arrays.toString(strs));//[abcdeag, abcdefg, abcdehg]
Find: binarySearch()
// *************Find binarySearch()**************** char[] e = { 'a', 'f', 'b', 'c', 'e', 'A', 'C', 'B' }; System.out.println("Arrays.binarySearch(e, 'c'): "); int s = Arrays.binarySearch(e, 'c'); System.out.println("character c At array location:" + s);
Compare: equals()
// *************Compare equals**************** char[] e = { 'a', 'f', 'b', 'c', 'e', 'A', 'C', 'B' }; char[] f = { 'a', 'f', 'b', 'c', 'e', 'A', 'C', 'B' }; /* * The number of elements is the same, and the elements in the same location are the same. In addition, if both array references are null, they are considered equal. */ // Output true System.out.println("Arrays.equals(e, f):" + Arrays.equals(e, f));
Fill:? fill()
// *************Fill (batch initialization)**************** int[] g = { 1, 2, 3, 3, 3, 3, 6, 6, 6 }; // Reassign values for all elements in the array Arrays.fill(g, 3); System.out.println("Arrays.fill(g, 3): "); // Output: 333333333 for (int i : g) { System.out.print(i); } // Line feed System.out.println(); int[] h = { 1, 2, 3, 3, 3, 3, 6, 6, 6, }; // Reallocate the value of the specified range element in the array Arrays.fill(h, 0, 2, 9); System.out.println("Arrays.fill(h, 0, 2, 9);: "); // Output: 993333666 for (int i : h) { System.out.print(i); }
Transfer list asList()
// *************To list asList()**************** /* * Returns a list of fixed sizes supported by the specified array. * (Change the list returned to write array.) As a bridge between array based and collection based API s, this method is combined with Collection.toArray(). * The returned list is serializable and implements RandomAccess. * This method also provides a convenient way to create a fixed size list initialized with several elements as follows: */ List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); System.out.println(stooges);
To string ()
// *************To string ()**************** /* * Returns a string representation of the contents of the specified array. */ char[] k = { 'a', 'f', 'b', 'c', 'e', 'A', 'C', 'B' }; System.out.println(Arrays.toString(k));// [a, f, b, c, e, A, C, B]
Copy of ()
// *************copy**************** // copyOf method implements array copy, h is array, 6 is copy length int[] h = { 1, 2, 3, 3, 3, 3, 6, 6, 6, }; int i[] = Arrays.copyOf(h, 6); System.out.println("Arrays.copyOf(h, 6);: "); // Output: 993333 for (int j : i) { System.out.print(j); } // Line feed System.out.println(); // copyOfRange copies the specified range of the specified array to the new array int j[] = Arrays.copyOfRange(h, 6, 11); System.out.println("Arrays.copyOfRange(h, 6, 11): "); // The output is 66600 (there are only 9 elements in the H array, which is copied from index 6 to index 11, so the shortage is 0) for (int j2 : j) { System.out.print(j2); } // Line feed System.out.println();