Guava & ndash; Optional, guavaoptional

Source: Internet
Author: User

Guava-Optional, guavaoptional

Excessive use of null may lead to a large number of buckets. In the underlying code of Google code, 95% of collection classes do not accept null values by default. For a null value, it is better to reject null with a quick failure than to accept it by default.

In addition, the meaning of null itself is vague. For example, if the return value of null is returned, for example, Map. get (key) returns null, either because the value corresponding to the key is null or the key does not exist in the map. Null can also be used to indicate failure or success, or anything. Using other values instead of null can make the meaning of the Code clearer.

In some cases, null should be used. In terms of memory and speed, null is cheap and is inevitable in the array of objects.

For the above reason, most of the Guava tools are designed as fast failures for null. In addition, Guava provides some tools to facilitate the use of null.

Actual Case

Do not use null in Set, or use null as the key value of Map. Replacing null with a special value can make the search semantics clearer.

If you want to use null as the value of Map, it is better not to put the entry into Map, but to maintain the "null" key Set with a separate Set. Because the values of a key in Map are null and no key value in Map is confusing.

If you need to use null in the List and the List is sparse, Map <Integer, E> may be better.

If null is required, but the null value cannot work with the Guava set, you can only select another method, such as Collections. unmodifiableList in JDK to replace ImmutableList in Guava.

Optional

Guava designs Optional to solve the null problem. Optional <T> indicates a reference of the T type that may be null. The Optional instance either contains a non-null reference or does not contain anything (absent), and never contains a null value reference. You can use Optional instead of null.

Optional not only gives null meaning, but also increases readability. It is also a silly protection. Optional forces you to actively think about the situation where the reference is true, because you must explicitly obtain the reference from Optional.

Possible applications of Optional:

  • The return value is used to replace null as the return value.
  • It is used to distinguish between "unknow" (for example, Map does not contain) and "known to have no value" (for example, Map contains the key and the value is Optional. absent ()).
  • It is used to wrap null references and is used in a collection that does not support null.

Create Optional (both static methods)
Optional. of (T) Creates the Optional instance specified for reference and throws NullPointException on the null value. We recommend that you directly pass constant parameters.
Optional. absent () Create a reference to the missing Optional instance
Optional. fromNullable (T) Creates an Optional instance of the specified reference. If the reference is null, the Optional instance is missing.
assertEquals("training", Optional.of("training").get());Optional<String> optionalName = Optional.absent();assertFalse(optionalName.isPresent());// Non-null instanceOptional<String> optionalName = Optional.fromNullable("bob");assertEquals("bob", optionalName.get());// null instanceassertSame(Optional.absent(), Optional.fromNullable(null));

Query Method (both non-static methods)
Boolean isPresent () Returns true if the Optional contains a non-null reference.
T get () Returns the reference contained in Optional. If the reference is missing, an IllegalStateException is thrown.
T or (T) Returns the reference contained in Optional. If the reference is missing, the default value is returned.
T orNull () Returns the reference contained in Optional. If the reference is missing, null is returned.
Set <T> asSet () Returns the variable singleton set contained in Optional. If it is null, an empty set is returned.

public void testIsPresent_no() {        assertFalse(Optional.absent().isPresent());    }    public void testIsPresent_yes() {        assertTrue(Optional.of("training").isPresent());    }    public void testGet_absent() {        Optional<String> optional = Optional.absent();        try {            optional.get();            fail();        } catch (IllegalStateException expected) {        }    }    public void testGet_present() {        assertEquals("training", Optional.of("training").get());    }        public void testOr_T_present() {        assertEquals("a", Optional.of("a").or("default"));    }    public void testOr_T_absent() {        assertEquals("default", Optional.absent().or("default"));    }    public void testOrNull_present() {        assertEquals("a", Optional.of("a").orNull());    }    public void testOrNull_absent() {        assertNull(Optional.absent().orNull());    }    public void testAsSet_present() {        Set<String> expected = Collections.singleton("a");        assertEquals(expected, Optional.of("a").asSet());    }    public void testAsSet_absent() {        assertTrue("Returned set should be empty", Optional.absent().asSet().isEmpty());    }    public void testAsSet_presentIsImmutable() {        Set<String> presentAsSet = Optional.of("a").asSet();        try {            presentAsSet.add("b");            fail();        } catch (UnsupportedOperationException expected) {        }    }    public void testAsSet_absentIsImmutable() {        Set<Object> absentAsSet = Optional.absent().asSet();        try {            absentAsSet.add("foo");            fail();        } catch (UnsupportedOperationException expected) {        }    }

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.