“This is the second day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”
Collections is a JDK utility class that comes under the java.util package. It provides a set of static methods that allow you to manipulate Collections as part of the Collections framework.
PS: Star this kind of thing, can only ask, do not ask for no effect, iron son, “The Path to Java Programmer advancement” on GitHub has harvested 556 stars, iron son hurry to dot, hit 600 star!
Github.com/itwanger/to…
Remember the Arrays utility class we talked about earlier? You can go back and brush it up.
The usage of Collections is very simple. Type Collections in Intellij IDEA. Then you can look at the method it provides and look at the method name and parameters to see what the method does.
In order to save your learning time, I have classified these methods and listed some simple examples.
01. Sort operations
reverse(List list)
: Reverse ordershuffle(List list)
: Shuffle the cards, shuffle the ordersort(List list)
: Natural ascending ordersort(List list, Comparator c)
: Sort by custom comparatorswap(List list, int i, int j)
: Swaps the positions of the elements in positions I and j
Here’s an example:
List<String> list = new ArrayList<>();
list.add("Silent King II.");
list.add("Silent King three.");
list.add("The Silent King iv.");
list.add("The Silent Five.");
list.add("The Sixth King of Silence.");
System.out.println("Original order:" + list);
/ / reverse
Collections.reverse(list);
System.out.println("After reversal:" + list);
/ / shuffle
Collections.shuffle(list);
System.out.println("After shuffling:" + list);
// Natural ascending order
Collections.sort(list);
System.out.println("After natural ascending order:" + list);
/ / exchange
Collections.swap(list, 2.4);
System.out.println("After exchange:" + list);
Copy the code
After the output:
Original order: Silence King two, Silence King three, Silence King four, Silence King Five, Silence King six reverse order: Silence King six, Silence King five, Silence King four, Silence King Three, Silence King two King Of Silence III, King of Silence II, King of Silence V, King of Silence VI, King of Silence IVCopy the code
02. Search operation
binarySearch(List list, Object key)
Binary search, if the List has been sortedmax(Collection coll)
: Returns the largest elementmax(Collection coll, Comparator comp)
: Returns the largest element according to the custom comparatormin(Collection coll)
: Returns the smallest elementmin(Collection coll, Comparator comp)
: Returns the smallest element according to the custom comparatorfill(List list, Object obj)
: fills with the specified objectfrequency(Collection c, Object o)
: Returns the number of occurrences of the specified object
Here’s an example:
System.out.println("Maximum element:" + Collections.max(list));
System.out.println("Smallest element:" + Collections.min(list));
System.out.println("Number of occurrences:" + Collections.frequency(list, "Silent King II."));
// Binary lookup is called without sorting, the result is indeterminate
System.out.println("Binary search results before sorting:" + Collections.binarySearch(list, "Silent King II."));
Collections.sort(list);
// After sorting, the search result is as expected
System.out.println("Sorted binary search result:" + Collections.binarySearch(list, "Silent King II."));
Collections.fill(list, "Silent bastard.");
System.out.println("Result after filling:" + list);
Copy the code
After the output:
Original order: [Silent King II, Silent King III, Silent King IV, Silent King V, Silent King VI] Maximum element: Silent King iv Minimum element: Silent King III Silent bastard, silent bastard, silent bastard, silent bastard, silent bastardCopy the code
03. Synchronous control
Hashmaps are thread-unsafe, as we discussed earlier. ArrayList is also thread-unsafe and cannot be used in a multithreaded environment. The Collections utility class provides multiple synchronizedXxx methods that return a synchronized object to address the security issues associated with accessing Collections in multiple threads.
It’s also very simple to use:
SynchronizedList synchronizedList = Collections.synchronizedList(list);
Copy the code
Take a look at the SynchronizedList source code, which simply locks methods with the synchronized keyword.
static class SynchronizedList<E>
extends SynchronizedCollection<E>
implements List<E> {
private static final long serialVersionUID = -7754090372962971524L;
final List<E> list;
SynchronizedList(List<E> list) {
super(list);
this.list = list;
}
public E get(int index) {
synchronized (mutex) {return list.get(index);}
}
public void add(int index, E element) {
synchronized (mutex) {list.add(index, element);}
}
public E remove(int index) {
synchronized (mutex) {returnlist.remove(index); }}}Copy the code
In this case, it’s about as efficient as Vector and Hashtable (which have been around since JDK 1.0) that simply add synchronized to their methods, and these collection classes are largely obsolete and barely used.
public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess.Cloneable.java.io.Serializable
{
public synchronized E get(int index) {
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
return elementData(index);
}
public synchronized E remove(int index) {
modCount++;
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
E oldValue = elementData(index);
int numMoved = elementCount - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--elementCount] = null; // Let gc do its work
returnoldValue; }}Copy the code
Instead, use CopyOnWriteArrayList and ConcurrentHashMap in the package. We’ll talk about that in concurrent programming.
Immutable set
emptyXxx()
: Creates an empty immutable setsingletonXxx()
: Creates an immutable set with only one elementunmodifiableXxx()
: Makes an immutable collection for the specified collection
Here’s an example:
List emptyList = Collections.emptyList();
emptyList.add("Not empty");
System.out.println(emptyList);
Copy the code
This code throws an error when executed.
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at com.itwanger.s64.Demo.main(Demo.java:61)
Copy the code
This is because collections.emptyList () returns an internal class emptyList for Collections, And EmptyList did not override the parent class AbstractList add (int index, E element) method, so the execution of UnsupportedOperationException throws does not support this operation.
This comes from analyzing the source code of the Add method. The emptyList method is final, and the EMPTY_LIST returned is final as well. There are indications that emptyList returns an immutable object and cannot be modified.
public static final <T> List<T> emptyList(a) {
return (List<T>) EMPTY_LIST;
}
public static final List EMPTY_LIST = new EmptyList<>();
Copy the code
05, other
Two more methods are commonly used:
addAll(Collection<? super T> c, T... elements)
To add elements to the collectiondisjoint(Collection<? > c1, Collection<? > c2)
, to determine whether two sets have no intersection
Here’s an example:
List<String> allList = new ArrayList<>();
Collections.addAll(allList, "King Of Silence ix."."King of Silence x"."Silent King II.");
System.out.println("After the addAll:" + allList);
System.out.println("Is there no intersection:" + (Collections.disjoint(list, allList) ? "Yes" : "No." "));
Copy the code
After the output:
[King Of Silence ii, King of Silence III, King of Silence IV, King of Silence V, King of Silence VI] whether there is no intersection: NoCopy the code
As a whole, the Collections utility class acts as a steward of the Collections framework, providing some very handy methods to call and very easy to learn. Look at the method comments to get a sense of what to do.
But it’s one thing to use the tool, it’s another to use it. Whether or not you can improve your coding level depends largely on whether or not you have to drill the source code, see these masters of JDK design how to write code, learn a trick and a half, in the work or can quickly stand out.
I’m afraid the JDK designers are the best teachers in the world, the documentation couldn’t be more detailed, the code couldn’t be more elegant, and basically the ultimate in performance.
One could argue that utility classes are useless, just methods to call, but that would be wrong: if you were writing, could you write Collections?
This is a question for the expert to ponder.
This is the 64th installment in the Java Programmer’s Path to Advancement column. Java programmer advanced path, humorous, easy to understand, extremely friendly and comfortable for Java beginners 😘, including but not limited to Java syntax, Java collection framework, Java IO, Java concurrent programming, Java virtual machine and other core knowledge points.
Github.com/itwanger/to…
Bright white and dark PDF versions are ready to be better Java engineers. Go!