Today, the boss asked ordinary young people and literary youth to write a piece of sayhello code, which requires the following: when the user name is null, it is called "Martian"
Later, the common youth and literary youth submitted the code.
Code of ordinary youth:
Public void ordinary youth _ sayhello (string name) {If (name = NULL) {name = "Martian";} system. out. println ("hello," + name );}
Code for young artists:
Import COM. google. common. base. optional; Public void literary youth _ sayhello (string name) {name = optional. fromnullable (name ). or ("Martian"); system. out. println ("hello," + name );}
The Code of Young People in literature and art is the same as that of ordinary young people. But it seems to be a little cool.
What is the most common exception in our Java code? It is definitely nullpointexception. It is too easy to ignore null processing.
In guava, the optional class is used to force young people to pay attention to null judgment.
Other methods of optional
| Optional <t>. Of (t) |
Assign a value to optional. When T is null, directly throw nullpointexception. We recommend that you directly transfer constants when calling this method, instead of variables. |
| Optional <t>. fromnullable (t) |
Assign value to optional. If t is null, the default value is used. We recommend that you use it with the or method. |
| Optional <t>. Absent () |
Assign a value to optional. Use the default value. |
| T or (t) |
If the value of optional is null, return with the value given by or. A good friend with fromnullable |
| T get () |
If the value of optional is null, illegalstateexception is thrown and the value of optional is returned. |
| Boolean ispresent () |
Returns true if optional has a value. |
| T ornull () |
If optional is null, return null. Otherwise, return the value of optional. |
| Set <t> asset () |
Convert the value in optional into a set to return. Of course, there is only one value, or it is empty. When the value is null. |
Question:
System. Out. println (optional. of (1). Of (2). of (3). Asset (). Size ());
What will be printed?
Answer: 1
Application of guava optional