Guava study notes: Immutable (immutable) set

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

  No variable set, as the name suggests is set cannot be modified. A collection of data items is provided at the time of creation, and throughout the life cycle can not be changed.

  Why use immutable objects? The immutable object has the following advantages:

    1 the unreliable customer code base, it is safe to use, can be in the untrusted class in the safe use of these objects

    The 2 thread safe: immutable object security in multi thread, no race conditions

    3 do not need to support variability, as far as possible to save space and time overhead. All immutable sets than the variable set to achieve more efficient use of memory (analysis)

    4 can be used as a constant, and the expectation in the future remain constant

  The immutable object can be naturally used as constant, because they are not variable for the use of the immutable object, it is a very good defensive programming (defensive programming) technology practice.

  Implementation of immutable JDK collection

  Collections.unmodifiableXXX provides a series of methods in JDK to realize the immutable sets, but there are some problems, we look at a specific example:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;

public class ImmutableTest {
    public void testJDKImmutable(){                                                                                                                                                                                                                                    
        List<String> list=new ArrayList<String>();                                                                               
        List<String> unmodifiableList=Collections.unmodifiableList(list); 
        List<String> unmodifiableList1=Collections.unmodifiableList(Arrays.asList("a","b","c")); 
        String temp=unmodifiableList.get(1);
        System.out.println("unmodifiableList [0]: "+temp);
        System.out.println("list add a item after list:"+list);
        System.out.println("list add a item after unmodifiableList:"+unmodifiableList);
        System.out.println("unmodifiableList add a item after list:"+unmodifiableList1);
        System.out.println("unmodifiableList add a item after list:"+unmodifiableList);        


[a, b, c]
[a, b, c]
[a, b, c]
unmodifiableList [0]: b
list add a item after list:[a, b, c, baby]
list add a item after unmodifiableList1:[a, b, c, baby]

  Note: Collections.unmodifiableList is not really the immutable sets, when the original set of modifications, immutable sets also changes. Immutable sets can not modify the collection data, when forced to modify the error when, at the end of two in an instance of add can directly throw can not modify error.

  Summarize the Collections.unmodifiableXXX method of the JDK to achieve some problem set immutable:

  1 it is clumsy tedious this method you have to use in every defensive programming copy.

  2 it's not safe: if the object reference original packaged collection classes, the method returns a collection is not really can not be changed.

  3: the essence of low efficiency because the data structure it returns is still the original collection class, so its operation expenses, including concurrent modification under examination, additional data in table space hash and the original collection is the same.

  Guava immutable collection

  Guava provides a standard set of JDK classes in the immutable version of the simple and convenient implementation, and some special collections of immutable Guava's own implementation. When you do not want to modify a collection class, or want to make a set of constants class, using the immutable collection classes is one of the best programming practices.

Note: each Guava immutable collection classes have refused to null value. We did the Google internal code of the comprehensive survey, and found that only 5% of cases set to allow null values, while 95% cases had refused to null value. If you really need to accept the null value of the collection classes, you can consider using Collections.unmodifiableXXX.

  The Immutable collection method:

  A immutable collection can have several ways to create:

  1 using the copyOf method, for example, ImmutableSet.copyOf(set)

  2 using the of method, for example, ImmutableSet.of ("a", "B", "C") or ImmutableMap.of("a", 1, "b", 2)

  3 using the Builder class


    public void testGuavaImmutable(){
        List<String> list=new ArrayList<String>();
        System.out.println("list: "+list);
        ImmutableList<String> imlist=ImmutableList.copyOf(list);
        System.out.println("imlist: "+imlist);
        ImmutableList<String> imOflist=ImmutableList.of("peida","jerry","harry");
        System.out.println("imOflist: "+imOflist);
        ImmutableSortedSet<String> imSortList=ImmutableSortedSet.of("a", "b", "c", "a", "d", "b");
        System.out.println("imSortList: "+imSortList);
         System.out.println("list add a item after list:"+list);
         System.out.println("list add a item after imlist:"+imlist);
         ImmutableSet<Color> imColorSet =
                   .add(new Color(0, 255, 255))
                   .add(new Color(0, 191, 255))


list: [a, b, c]
imlist: [a, b, c]
imOflist: [peida, jerry, harry]
imSortList: [a, b, c, d]
list add a item after list:[a, b, c, baby]
list add a item after imlist:[a, b, c]
imColorSet:[java.awt.Color[r=0,g=255,b=255], java.awt.Color[r=0,g=191,b=255]]

  There are exceptions for sorting collections, because the order of the elements in the sets when it is fixed. For example, ImmutableSet.of ("a", "B", "C", "a", "d", "B"), for the set of traversal sequence is"a", "b", "c", "d".

  A more intelligent copyOf

  Intelligent copyOf than you might think, ImmutableXXX.copyOf will avoid copying elements operating - ignore the details in the right circumstances, but its implementation is usually very “ intelligent ”. For example:

    public void testCotyOf(){
        ImmutableSet<String> imSet=ImmutableSet.of("peida","jerry","harry","lisa");
        System.out.println("imSet: "+imSet);
        ImmutableList<String> imlist=ImmutableList.copyOf(imSet);
        System.out.println("imlist: "+imlist);
        ImmutableSortedSet<String> imSortSet=ImmutableSortedSet.copyOf(imSet);
        System.out.println("imSortSet: "+imSortSet);
        List<String> list=new ArrayList<String>();
        for(int i=0;i<20;i++){
        System.out.println("list: "+list);
        ImmutableList<String> imInfolist=ImmutableList.copyOf(list.subList(2, 18));
        System.out.println("imInfolist: "+imInfolist);
        int imInfolistSize=imInfolist.size();
        System.out.println("imInfolistSize: "+imInfolistSize);
        ImmutableSet<String> imInfoSet=ImmutableSet.copyOf(imInfolist.subList(2, imInfolistSize-3));
        System.out.println("imInfoSet: "+imInfoSet);


imSet: [peida, jerry, harry, lisa]
imlist: [peida, jerry, harry, lisa]
imSortSet: [harry, jerry, lisa, peida]
list: [0x, 1x, 2x, 3x, 4x, 5x, 6x, 7x, 8x, 9x, 10x, 11x, 12x, 13x, 14x, 15x, 16x, 17x, 18x, 19x]
imInfolist: [2x, 3x, 4x, 5x, 6x, 7x, 8x, 9x, 10x, 11x, 12x, 13x, 14x, 15x, 16x, 17x]
imInfolistSize: 16
imInfoSet: [4x, 5x, 6x, 7x, 8x, 9x, 10x, 11x, 12x, 13x, 14x]

  In this code, the ImmutableList.copyOf (imSet) will be smart to return the time complexity is constant in ImmutableSet imSet.asList().

  In general, ImmutableXXX.copyOf (ImmutableCollection) can avoid the linear complexity of the copy operation. As in the following cases:

  This operation may be used by the constant encapsulated data structure complexity operations. But such as ImmutableSet.copyOf (list) can not be achieved in the constant complexity.

  This will not lead to a memory leak - for example, you have a ImmutableList<String> imInfolist, then you explicitly operation ImmutableList.copyOf (imInfolist.subList (0, 10)). This operation can avoid unexpected hold no longer needed elements in hugeList reference.

  It does not change the set of semantic - like ImmutableSet.copyOf (myImmutableSortedSet) such explicit copy operations, because in ImmutableSet hashCode () and equals () meaning and the comparator based ImmutableSortedSet is different.

  The performance overhead is helpful to optimize the characteristics of defensive programming.

  The asList method

  All of the immutable set to asList () provided in the form of the ImmutableList view (view). For example, you put the data in ImmutableSortedSet, you can call sortedSet.asList ().Get (k) to obtain the set of k elements.

  The returned ImmutableList is often a constant complexity view, rather than a true copy. That is to say, this returns a collection of more intelligent than general List for example, it would be more efficient methods such as contains.


    public void testAsList(){
        ImmutableList<String> imList=ImmutableList.of("peida","jerry","harry","lisa","jerry");
        System.out.println("imList: "+imList);
        ImmutableSortedSet<String> imSortList=ImmutableSortedSet.copyOf(imList);
        System.out.println("imSortList: "+imSortList);
        System.out.println("imSortList as list: "+imSortList.asList());


imList: [peida, jerry, harry, lisa, jerry]
imSortList: [harry, jerry, lisa, peida]
imSortList as list: [harry, jerry, lisa, peida]

  The Guava collection and immutable correspondence

The variable set type source: JDK or variable set Guava? Guava immutable sets Collection JDK ImmutableCollection List JDK ImmutableList Set JDK ImmutableSet SortedSet/NavigableSet JDK ImmutableSortedSet Map JDK ImmutableMap SortedMap JDK ImmutableSortedMap Multiset Guava ImmutableMultiset SortedMultiset Guava ImmutableSortedMultiset Multimap Guava ImmutableMultimap ListMultimap Guava ImmutableListMultimap SetMultimap Guava ImmutableSetMultimap BiMap Guava ImmutableBiMap ClassToInstanceMap Guava ImmutableClassToInstanceMap Table Guava ImmutableTable

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Sammy at November 14, 2013 - 4:38 PM