【发布时间】:2018-10-31 14:30:14
【问题描述】:
我有一个 ArrayList 的 Car 对象。我正在检查空值和 Germany 并在 if 条件内执行某些操作。
但我想使用Optional 类来避免检查空值。我该如何使用它?
这是我的代码:
public class TestOptional {
public static List<Car> getCarList() {
List<Car> carList = new ArrayList<Car>();
carList.add(new Car("Benz", 2016, "Germany"));
carList.add(new Car("Rolls Royce", 2015, "Russia"));
carList.add(new Car("BMW", 2017, null));
carList.add(new Car("Maruti", 2014, ""));
return carList;
}
public static void main(String args[]) {
List<Car> carList1=getCarList();
for(Car c:carList1) {
if(c.getCountry() != null && c.getCountry().equalsIgnoreCase("Germany")) {
System.out.println(c.getCarName()+" car is from Germany");
}
}
Optional<Car> optional = getCarList();
}
}
我收到此错误:
`Type mismatch: cannot convert from List<Car> to Optional<Car>`
我不确定如何在 List 对象上使用 Optional 类。
请找到我的汽车代码:
public class Car {
private String carName;
private int year;
private String country;
public Car(String carName, int year, String country) {
this.carName = carName;
this.year = year;
this.country = country;
}
public String getCarName() {
return carName;
}
public int getYear() {
return year;
}
public String getCountry() {
return country;
}
}
** 更新 1 **
我开始探索一些 Java8 功能,我发现了 Optional 类,我想使用它。我找到了Optional类的用法。
在 Java 8 中,我们在 java.util 包中新引入了一个 Optional 类。引入此类是为了避免我们在代码中不执行 null 检查时经常遇到的 NullPointerException。使用这个类我们可以很容易地检查一个变量是否有空值,通过这样做我们可以避免 NullPointerException。
所以,我尝试为我的 ArrayList 应用 Optional 类,并且我想避免对我的 ArrayList 中的所有对象进行空检查。
List<Car> carList1=getCarList();
for(Car c:carList1) {
if(c.getCountry() != null && c.getCountry().equalsIgnoreCase("Germany")) {
System.out.println(c.getCarName()+" car is from Germany");
}
}
在上面的代码中,我检查 Country 对象是否为 null。所以在这里我想避免编写空检查代码(使用可选类)。
【问题讨论】:
-
一个
Optional<Car>包含零辆或一辆辆汽车。您的列表包含 四辆 辆汽车。Optional<Car>应该包含什么? -
如果我理解正确,您是否试图避免对
country进行空检查? -
您为什么希望
List<Car>更改为Optional<Car>?根据您的问题,Car中的某些内容需要更改(例如,为getCountry()返回Optional<String>?您还没有将Car代码放在您的问题中。 -
@Thiru - 是的,我想避免对国家/地区进行空检查
-
解决这个问题的一个好方法是首先通过将它放在你的构造函数中来使创建具有空国家的汽车成为不可能:
this.country = Objects.requireNonNull(country, "Country cannot be null");