Guava Learning notes-basic tools

Source: Internet
Author: User
using the optional class to avoid null

Null represents uncertainty, it is possible that this object does not exist (most of the time); It may be success or failure; it may be an object exists but the object is empty (in the collection). Any uncertainty may put the program in danger. The optional class forces you to think about the true meaning of NULL, remove the ambiguity of NULL, and allow the program to gracefully handle null situations. You can avoid throwing null pointer exceptions. The biggest advantage of using optional in addition to giving null semantics and increasing readability is that it is a kind of dummy protection. Optional forces you to think positively about missing references because you have to explicitly get references from optional. The direct use of NULL is easy to forget some situations, although findbugs can help find null-related problems, but we still think that it does not accurately locate the source of the problem.

For example, you would want to find the value of the corresponding key from a map collection, such as the following methods. When the result returns NULL, the key does not exist. Or is the value of this key corresponding to NULL.

    Public integer findfrommap (integer key) {
        map<string, integer> Map = Maps.newhashmap ();
        Map.put ("foo", null);
        Map.put ("Bar", 1);

        System.out.println (Map.get (key));
        return Map.get (key);
    }

The optional class may solve this problem by forcing you to return null, and be sure to return a meaningful value.

        Used when not present, do not return null
        optional<string> absentstring = Optional.absent ();

        Determines whether the existence is not NULL, if NULL immediately returns null pointer exception
        optional<string> presentstring = optional.of ("must exist");

        is not sure if it is an empty
        optional<string> possiblenullstring = optional.fromnullable (findsomething (param));

        If there is no return default value
        String defaultstring = possiblenullstring.or ("not Exist");

        Determine if there is an
        if (Possiblenullstring.ispresent ()) {

            //Return existing value
            possiblenullstring.get ();
        }

        Returns a single case invariant set Possiblenullstring.asset () containing a reference to the optional
        ;
Precondition : Make the criteria in the method easier to check
    The public void Testpreconditions (string param1, String param2, Boolean state) {
        //checks to see if expression is true to check the arguments passed to the method. The exception illegalargumentexception
        checkargument (param1!= null && param2 null) thrown when the check fails;
        Checks whether the state is true, and the exception that is thrown when the check fails illegalstateexception
        checkstate (state, State must is false);
        Check for null, check for exceptions thrown when failure nullpointerexception
        checknotnull (param1);
        Checknotnull (param2, "param2 can not be null!");
        Checks whether index is valid for a list, string, or array as an indexed value. Index>=0 && index<size *
        int index = 1;
        int size = ten;
        Checkpositionindex (index, size);
        Checks whether index is valid for a list, string, or array as a positional value. Index>=0 && index<=size *
        checkelementindex (index, size);
    
Object Method

equals
Avoid throwing NULL pointer exceptions

Hashcode
Hashing [hash] operations with all fields of an object should be simpler. Guava Objects.hashcode (Object ...) A reasonable, sequentially-sensitive hash value is computed for the passed-in field sequence. You can use Objects.hashcode (field1, Field2, ..., fieldn) instead of manually calculating hash values

Tostring
More convenient to use

    @Test public
    void Testojbects () {
        Boolean flag = Objects.equal ("A", "B");
        Objects.hashcode ("AAA", "BBB");
        String string =  Moreobjects.tostringhelper (this). Add ("X", 1). AddValue (123). ToString ();
        String expected = "testguava{x=1, 123}";
        Assertequals (expected, string);
    
chain-style comparator
   @Test public void Testorder () {function<string, string> converttoupper = new function<string, Stri  Ng> () {@Override public string apply (string input) {if (input = null | |
                = = "") return null;
            return Input.touppercase ();
        }
        };
        When reading a sequencer generated by a chained call, you should read it backwards.
        ordering<string> ordering = Ordering.natural (). Nullslast (). Onresultof (Converttoupper);
        List<string> strings = Arrays.aslist ("B", "C", NULL, "a");
        list<string> expectedstring = ordering.sortedcopy (strings);
        list<string> actualstring = Arrays.aslist ("A", "B", "C", null);
        Assertequals (expectedstring, actualstring);
        Gets the largest k element in an iterator object.
        list<string> string2 = Arrays.aslist ("A", "B", "D");
        Assertequals (Ordering.greatestof (string2, 2), Arrays.aslist ("D", "B")); Returns the smallest of two parameters.
        If equal, the first argument is returned. List<string> string3 = arrays.aslist ("E", "F", "G");
        Assertequals (Ordering.min (STRING3), "E");
 Returns the smallest K-native Ordering.leastof (String3, 2);}

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.