Optional understand

Optional understand

1. Meaning

OptionalIs a container object, the container may contain a non-null value or may not contain non-null value. The main purpose is to circumvent the NPE abnormal (incoming object is null result).

  • If the value exists, by the isPresentmethod returns true, by getobtaining the value method

Optional Also it provides additional methods that come into play, depending on whether there is value.

note

Do not Optionaluse objects hashcode, , synchronized, ==otherwise it will affect unpredictable. Because Optionalthe class based on the value.

Class-based value (Value-based Classes)

About What is Value-based Clases, I found an article Oracle official documentation: Value-based the Classes

Some (such as java.util.Optional and java.time.LocalDateTime) is based on the value. Examples has the following characteristics based on the values ​​of:

  • Has the final properties can not be changed (although it may contain references to mutable objects)
  • With equals(), hashCode(), toString()the state of implementation of the method and implementation depends on the instance only changes its status, independent of external objects or variables
  • Not used the identity sensitive operations, using ==compare two instances, instance information acquired using the hashcode using synchronizedacquire internal lock
  • If two instances of the same is a equals()method and not==
  • The method of construction is not disclosed, but by generating instance factory method (Factory method)
  • If the two instances of the same, can replace each other, and do not have different behavior

2. Optional class method

2.1 Constructor
private Optional(T value) {
    this.value = Objects.requireNonNull(value);
}
  • Optional It is a container, which container package with a value that is generic

  • Since the privatization of the constructor, it is not new by new Optionalobjects, only through the static factory method to construct the object

2.2 Creating Optional object methods
  • of: Returns the value of a container object is not null, this method requires the caller when the call of the method, the parameter value is not empty, otherwise it will throw an NPE exception.

    public static <T> Optional<T> of(T value) {
        return new Optional<>(value);
    }
  • ofNullable: A structure may be empty or may not be empty optional subject.

    public static <T> Optional<T> ofNullable(T value) {
        return value == null ? empty() : of(value);
    }
  • empty: Return null object container is

    public static<T> Optional<T> empty() {
        @SuppressWarnings("unchecked")
        Optional<T> t = (Optional<T>) EMPTY;
        return t;
    }
2.3 Other methods
  • isPresent: Determining whether the object is present

  • get: Gets the value of the container

  • orElse: The value of the container is not empty, the print value; is empty, return the specified value.

    public T orElse(T other) {
        return value != null ? value : other;
    }
  • orElseGet: This method does not accept arguments. Value of the container is not empty, return value; empty, return specified value

    public T orElseGet(Supplier<? extends T> other) {
        return value != null ? value : other.get();
    }

    For example:

    System.out.println(optional.orElseGet(() -> "nihao"));
  • orElseThrow: The value of the container is not empty, return value; empty, an exception is thrown.

  • map: Mapping, a value mapped to another value. If there is value, then calling the mapping function to get its return value. If the return value is not null, then create a map that contains the return value of Optionala mapmethod returns a value, otherwise return emptyOptional

    public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
        Objects.requireNonNull(mapper);
        if (!isPresent())
            return empty();
        else {
            return Optional.ofNullable(mapper.apply(value));
        }
    }

    For example:

    System.out.println(optional.map(thecompant -> theCompany.getEmployees()).
                       orElse(Collections.emptylist()));

Note that
in the enterprise development, we often pass orElseto circumvent NPE exception.

3. Optional object should not be used as a method parameter

OptionalIt can not be serialized. So do not try to Optionalbe defined as a method parameter, which is also not declared in the class Optionalmember variable type. OptionalUsually only as a return value, to circumvent null pointer exception.

In use Optional, you should use functional programming style.

Guess you like

Origin www.cnblogs.com/weixuqin/p/11494905.html