Given the code fragments:
class Employee {
Optional<Address> address;
Employee(Optional<Address> address) {
this.address = address;
}
public Optional<Address> getAddress() {
return address;
}
}
class Address {
String city = "New York";
public String getCity() {
return city;
}
public String toString() {
return city;
}
}
and
Address address = null;
Optional<Address> addrs1 = Optional.ofNullable(address);
Employee e1 = new Employee(addrs1);
String eAddress = (addrs1.isPresent()) ? addrs1.get().getCity() : "City Not available";
System.out.println(eAddress);
What is the result?
A.
New York
B.
City Not available
C.
null
D. A NoSuchElementException is thrown at run time.
题解
Optional 类别的 ofNullable 方法允许传入参考为 null 的对象参数,来产生 Optional 对象。由于第 41 行的 address 变量为 null,因此会产生出空的 Optional 对象。
程序第 42 行,利用空的 Optional 对象来实体化新的 Employee 对象,这个没有问题。
程序第 43 行,先判断 Optional 对象的内容是否存在,由于这里使用的 Optional 对象是空的,因此会将「City Not available」字符串参考指派给 eAddress 变量保存。
最后输出「City Not available」。
若在程序有运行到「addrs1.get()」,将会因为 addrs1 所参考到的 Optional 对象的内容是空的,而抛出 NoSuchElementException 例外。但在这个题目中,使用了三元条件操作符来控制程序的流程,所以不会运行到「addrs1.get()」。
