"The beauty of Java code"---the Immutable (immutable) collection of guava

Source: Internet
Author: User

Immutable (immutable) collection

I. Overview

Guava is a library of Google, to make up for many aspects of the Java language deficiencies, many in the JAVA8 has been implemented, temporarily do not expand. Collections is a tool class provided by the JDK.

Guava the difference between immutable objects and the Collections tool class Unmodifiableset/list/map/etc:

Immutable Collections also change when the wrapper class of immutable collections created by collections changes , and Guava's immutable collection guarantees that they are indeed immutable .

1. implement immutable collection in JDK

Collections.unmodifiablexxx series methods are provided in the JDK to implement immutable collections, but there are some problems, let's look at a specific example:

 Public classimmutabletest {@Test Public voidtestjdkimmutable () {List<String> list=NewArraylist<string>(); List.add (A); List.add ("B"); List.add (C); //Create an immutable unmodifiablelist collection from the listList<string> unmodifiablelist=collections.unmodifiablelist (list);        System.out.println (unmodifiablelist); //adding elements through the listList.add ("ddd"); System.out.println ("Adding an element to the list:" +list); System.out.println ("Unmodifiablelist after adding elements through list:" +unmodifiablelist); //adding elements through UnmodifiablelistUnmodifiablelist.add ("Eee"); System.out.println ("Add an element to Unmodifiablelist:" +unmodifiablelist); }}

Operation Result:

By running the result we can see: Although unmodifiablelist can not add elements directly, but my list can add elements, and list changes will also make unmodifiablelist change.

So the collections.unmodifiablelist implementation is not a true immutable set.

2. Immutable collection of Guava

Guava provides a simple and convenient implementation of the immutable version of the standard collection class in the JDK, as well as the immutable implementation of some of Guava's own specialized collection classes. When you don't want to modify a collection class,

Or when you want to make a constant collection class, using the Immutable collection class is the best programming practice.

Note : the implementation of each guava immutable collection class rejects the null value. We did a full survey of Google's internal code, and found that only 5% of the collection classes allowed null values, while 95% of cases

Null values are rejected. In case you really need a collection class that can accept null values, you can consider using COLLECTIONS.UNMODIFIABLEXXX.

The immutable collection can be created in several ways:

1, with CopyOf method, for example, immutableset.copyof (set)

2, use of the method, for example, Immutableset.of ("A", "B", "C") or Immutablemap.of ("a", 1, "B", 2)

3. Using the Builder class

Example:

@Test Public voidtestguavaimmutable () {List<String> list=NewArraylist<string>(); List.add (A); List.add ("B"); List.add (C); 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); List.add ("Baby"); //The key is to see if this imlist also adds new elements.System.out.println ("See Imlist after adding a new element to the list:" +imlist); Immutableset<Color> Imcolorset =Immutableset.<Color>Builder (). Add (NewColor (0, 255, 255). Add (NewColor (0, 191, 255) . Build (); System.out.println ("Imcolorset:" +imcolorset); }

Running result: found that imlist has not changed.

There is an exception to the sorted collection, because the order of the elements is fixed when the collection is built. For example, Immutableset.of ("A", "B", "C", "a", "D", "B") are "a", "B", "C", "D" for this set's traversal order.

more Intelligent copyof

The Copyof method is smarter than you think, and immutablexxx.copyof avoids copying the elements in the right circumstances-ignoring the specifics, but its implementation is generally "smart". Such as:

@Test Public voidtestcotyof () {Immutableset<String> imset=immutableset.of ("Peida", "Jerry", "Harry", "Lisa"); System.out.println ("Imset:" +Imset); //set direct go to listImmutablelist<string> imlist=immutablelist.copyof (Imset); System.out.println ("Imlist:" +imlist); //List Direct Turn SortedSetImmutablesortedset<string> imsortset=immutablesortedset.copyof (Imset); System.out.println ("Imsortset:" +imsortset); List<String> list=NewArraylist<string>();  for(inti=0;i<=10;i++) {List.add (i+ "X"); } System.out.println ("List:" +list); //intercepting a collection part elementImmutablelist<string> iminfolist=immutablelist.copyof (List.sublist (2, 8)); System.out.println ("Iminfolist:" +iminfolist); }

Run results

Guava set and immutable correspondence relation
Variable collection type mutable collection Source: JDK or Guava? Guava Immutable Collection
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

This article refers to: Guava study notes: Immutable (immutable) collection thanks!

think too much, do too little, the middle of the gap is trouble. Want to have no trouble, either don't think, or do more. Lieutenant Colonel "12"

The beauty of Java code---Guava Immutable (immutable) collection

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.