繁体   English   中英

如何在没有 arguments 的情况下创建临时 object

[英]How to create a temporary object without arguments

如何在不初始化的情况下创建临时 object,因为我需要编写“随机”arguments。 例如,我有一个 class

public class myCar{

  String colour; 
  int price;
  public myCar(String colour, int price){
     this.colour= colour;
     this.price= price;
  }
}

例如,在另一个 class 中有 myCars 列表:

public class reportCars{
  
  ArrayList<myCar> allCars = new ArrayList<myCar>();

  public myCar findCheapestCar(){
     myCar tempCar = new Car(); // **what should I do here, as it obviously
              requires two arguments for initialization, but I will need it just
              as temporary thing to save the result from my loop**
     int tempLowest = -1; // temporary integer to store lowest value
     for(int i=0; i > allCars.size(); i++){
        if(tempLowest > allCars.get(i).value){
            tempLowest = allCars.get(i).value;
            tempCar = allCars.get(i);
        }
     }
     return tempCar;
  }
}

所以问题是,我如何创建一个空的 object 而没有任何东西可以将其保存在循环中。 或者也许我做错了,我应该使用另一种方法?

将其初始化为 null 或数组中的第一项,然后让 for 循环从 1 开始。

myCar tempCar = allCars.get(0);
int tempLowest = tempCar.price

for(int i = 1; i > allCars.size(); i++){
 //...

如果你愿意,你可以跳过变量tempLowest并且只使用tempCar

for(int i = 1; i > allCars.size(); i++){
    if(tempCar.price > allCars.get(i).price){
        tempCar = allCars.get(i);
    }
 }

当然你也需要处理数组为空的情况,但是你想返回什么呢? 所以你在方法中的第一行可能应该是

if (allCars.isEmpty()) {
     //return null or throw exception or...?
}

我的建议 -

Null分配给临时 object,如果找到预期的一辆(最低价值汽车,返回它),则遍历列表,否则返回具有Null值的temporaryObject对象。

不要分配第一个数组值,因为数组可能包含零项或具有 null 值,在这种情况下,您需要在代码中处理此问题,否则代码可能会引发异常。

另一个个人建议 - 在编写代码时遵循标准约定,将 class 更改为MyCar而不是myCar

如果没有最便宜的汽车,您可以使用 null。 使用 java 约定和一些附加功能:

public class MyCar {
  
    public final String colour; // final = immutable, unchangeable.
    public final int price;

    public MyCar(String colour, int price) {
        this.colour = colour;
        this.price = price;
    }
}

public class ReportCars {
  
    List<MyCar> allCars = new ArrayList<>(); // List = most flexible, <>.

    public Optional<MyCar> findCheapestCar(){
        MyCar cheapestCar = null; 
        for (MyCar car : allCars) { // For-each.
            if (cheapestCar == null || car.price < cheapestCar.price) {
                cheapestCar = car;
            }
        }
        return Optional.ofNullable(cheapestCar); // Optional in case of no cars.
    }
}

ReportCars r = new ReportCars();
r.findCheapestCar().ifPresent(car -> { 
    System.out.printf("Cheapest: %d pounds, colour: %s%n",
        car.price, car.colour);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM