Optional.of()
时间: 2024-05-14 12:14:23 浏览: 67
Optional类.md
Optional.of() is a method in the Java Optional class that creates an Optional object with a non-null value. It takes one parameter, the value that is to be wrapped in the Optional object.
For example, if we have a String variable "name" that we want to wrap in an Optional object, we can use Optional.of() as follows:
```
String name = "John";
Optional<String> optionalName = Optional.of(name);
```
This will create an Optional object "optionalName" with the value "John". If the "name" variable were null, this would result in a NullPointerException. Therefore, it is recommended to use Optional.ofNullable() instead if the value can be null.
阅读全文