Let's understand the immutable collection in Java in another way! ! !

Immutable collection example:

public static final ImmutableSet<String> COLOR_NAMES = ImmutableSet.of(
        "red",
        "orange",
        "yellow",
        "green",
        "blue",
        "purple");

class Foo {
    Set<Bar> bars;
    Foo(Set<Bar> bars) {
        this.bars = ImmutableSet.copyOf(bars); // defensive copy!
    }
}

Why use immutable collections

Immutable objects have many advantages, including:

  • When the object is called by an untrusted library, the immutable form is safe;

  • When immutable objects are called by multiple threads, there is no race condition problem

  • Immutable collections do not need to consider changes, so you can save time and space. All immutable collections have better memory utilization (analysis and test details) than their mutable forms;

  • Because immutable objects are fixed, they can be used safely as constants.

  • Creating immutable copies of objects is a good defensive programming technique. Guava provides simple and easy-to-use immutable versions for all JDK standard collection types and Guava's new collection types. The JDK also provides the Collections.unmodifiableXXX method to wrap the collection in an immutable form, but we think it is not good enough:

  • Bulky and cumbersome: Can not be used comfortably in all scenarios where you want to make defensive copies;

  • Unsafe: Make sure that no one modifies the original collection by reference, and the returned collection is in fact immutable;

  • Inefficiency: The wrapped collection still retains the overhead of the variable collection, such as checking of concurrent modifications, extra space for the hash table, and so on.

If you don't need to modify a certain collection, or want a certain collection to remain unchanged, it is a good practice to defensively copy it to an immutable collection.

Important note: All implementations of Guava immutable collections do not accept null values. We have done a detailed study on Google's internal code base and found that only 5% of the cases need to allow null elements in the collection, and the remaining 95% of the scenes fail quickly when encountering a null value. If you need to use null in immutable collections, please use the Collections.unmodifiableXXX method in the JDK. For more detailed suggestions, please refer to "Use and Avoid Null".

How to use immutable collections

Immutable collections can be created in several ways:

  • copyOf method, such as ImmutableSet.copyOf(set);
  • of method, such as ImmutableSet.of("a", "b", "c") or ImmutableMap.of("a", 1, "b", 2);
  • Builder tools such as
public static final ImmutableSet<Color> GOOGLE_COLORS =
        ImmutableSet.<Color>builder()
            .addAll(WEBSAFE_COLORS)
            .add(new Color(0, 191, 255))
            .build();

In addition, for ordered immutable collections, sorting is done when the collection is constructed, such as:

ImmutableSortedSet.of("a", "b", "c", "a", "d", "b");

It will sort the elements into a, b, c, d during construction.

CopyOf smarter than imagined

Please note that the ImmutableXXX.copyOf method will try to avoid making copies when it is safe-the actual implementation details are not known, but it is usually very smart, such as:

ImmutableSet<String> foobar = ImmutableSet.of("foo", "bar", "baz");
thingamajig(foobar);

void thingamajig(Collection<String> collection) {
    ImmutableList<String> defensiveCopy = ImmutableList.copyOf(collection);
    ...
}

In this code, ImmutableList.copyOf(foobar) will intelligently directly return foobar.asList(), which is a List view of ImmutableSet with constant time complexity. As an exploration, ImmutableXXX.copyOf(ImmutableCollection) will try to avoid linear time copy in the following situations:

  • It is possible to use the underlying data structure in constant time-for example, ImmutableSet.copyOf(ImmutableList) cannot be completed in constant time.
  • No memory leaks-for example, if you have a huge immutable collection ImmutableList hugeList, ImmutableList.copyOf(hugeList.subList(0, 10)) will be explicitly copied to avoid unnecessary holding of hugeList references .
  • Does not change the semantics-so ImmutableSet.copyOf(myImmutableSortedSet) will be copied explicitly, because ImmutableSet has different semantics for hashCode() and equals compared to the comparator-based ImmutableSortedSet. Avoiding linear copy when possible can minimize the performance overhead of defensive programming styles.

asList view

All immutable collections have an asList() method to provide an ImmutableList view to help you easily read collection elements in the form of a list. For example, you can use sortedSet.asList().get(k) to read the k-th smallest element from ImmutableSortedSet.

The ImmutableList returned by asList() is usually—not always—a cost-stable implementation of the view, rather than simply copying the elements into the List. In other words, the list view returned by asList is usually better than the average performance of the general list. For example, when the underlying collection supports it, it always uses the efficient contains method.

At last

Reply to the data by private message to receive a summary of Java interview questions from a major manufacturer + Alibaba Taishan manual + a learning guide for knowledge points + a summary of Java core knowledge points in a 300-page pdf document!

Insert picture description here

The content of these materials are all the knowledge points that the interviewer must ask during the interview. The chapter includes many knowledge points, including basic knowledge, Java collections, JVM, multi-threaded concurrency, spring principles, microservices, Netty and RPC, Kafka , Diary, design pattern, Java algorithm, database, Zookeeper, distributed cache, data structure, etc. file

Guess you like

Origin blog.csdn.net/weixin_46577306/article/details/107869428