如何创建不带参数的临时对象



如何在不初始化的情况下创建临时对象,因为我需要编写"random"参数。例如,我有一个类

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

例如,在另一个类中有list of 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;
}
}

问题是,如何创建一个空对象而不需要在循环中保存它。或者也许我做错了,我应该用另一种方法?

将其初始化为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分配给临时对象,如果找到预期的一个(最低值的车,返回它),则迭代列表,否则返回具有Null值的temporaryObject

不要赋数组的第一个值,因为数组可能包含零项或为空值,在这种情况下,你需要在代码中处理,否则代码可能会抛出异常。

另一个个人建议-在编写代码时遵循标准约定,将类更改为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);
});

最新更新