System.out.println("optional2失败了");
}
try {
Optional<Integer> optional3 = Optional.ofNullable(value1);
System.out.println("optional3创建了");
}catch (Exception e){
System.out.println("optional3失败了");
}
try {
Optional<Integer> optional4 = Optional.of(value2);
System.out.println("optional4创建了");
}catch (Exception e){
System.out.println("optional4失败了");
}
try {
Optional<Integer> optional5 = Optional.ofNullable(value2);
System.out.println("optional5创建了");
}catch (Exception e){
System.out.println("optional5失败了");
}
}

文章插图
2.3.3 值获取方法1)源码
public T get() {
if (value =https://www.huyubaike.com/biancheng/= null) {
throw new NoSuchElementException("No value present");
}
return value;
}
3)测试代码
public static void main(String[] args) {
Integer value1 = null;
Integer value2 = 1;
Optional<Integer> optional1 = Optional.ofNullable(value1);
Optional<Integer> optional2 = Optional.of(value2);
try {
Integer result=optional1.get();
System.out.println("optional1的值是:"+result);
}catch (Exception e){
System.out.println("optional1的值获取失败,原因:"+e.getMessage());
}
try {
Integer result=optional2.get();
System.out.println("optional2的值是:"+result);
}catch (Exception e){
System.out.println("optional2的值获取失败,原因:"+e.getMessage());
}
}

文章插图
2.3.4 判断方法1)源码
public boolean isPresent() {
return value != null;
}
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
public T orElse(T other) {
return value != null ? value : other;
}
public T orElseGet(Supplier<? extends T> other) {
return value != null ? value : other.get();
}
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (value != null) {
return value;
} else {
throw exceptionSupplier.get();
}
}
- isPresent(): 判断optional是否为空 , 如果空则返回false , 否则返回true
- ifPresent(Consumer c): 如果optional不为空 , 则将optional中的对象传给Comsumer函数
- orElse(T other): 如果optional不为空 , 则返回optional中的对象;如果为null , 则返回 other 这个对象 。
经验总结扩展阅读
- Go 源码解读|如何用好 errors 库的 errors.Is 与 errors.As() 方法
- Optional 常用方法总结
- 走到尽头结局解析?
- 西西里的美丽传说解析?
- LOL血港开膛手派克技能解析及玩法技巧?
- 王者荣耀孙策技能解析?
- 英魂之刃李探花出装打法解析?
- 王者荣耀中钟馗技能解析以及如何连招?
- 英雄联盟lol青钢影卡蜜尔技能玩法解析?
- 野荷塘网站源码,野荷塘网站模板哪里可以买到?