这是我的工作代码。
import java.util.ArrayList;
public class Cars {
String Type;
String Make;
String Model;
int Price;
int NoDoors;
public static void main(String [] args){
ArrayList <Cars> vehicleArray = new ArrayList<Cars>();
vehicleArray.add(new Cars("Car","Peugot","206",1495,5));
vehicleArray.add(new Cars("Car","BMW","M3",34495,3));
vehicleArray.add(new Cars("Car","FIAT","PUNTO",3495,5));
vehicleArray.add(new Cars("Car","FORD","GT",41495,3));
System.out.println("List of Cars :" + "\n");
for(Cars car : vehicleArray){
System.out.println("Type: " + car.getType());
System.out.println("Make: " + car.getMake());
System.out.println("Model: " + car.getModel());
System.out.println("Price: " + car.getPrice());
System.out.println("No of Doors: " + car.getDoors() + "\n");
}
Cars lowestPrice = vehicleArray.get(0);
for(Cars car : vehicleArray){
if(lowestPrice.Price>car.Price){
lowestPrice = car;
}
}
System.out.println("\n" + "Cheapest Car : ");
System.out.println("Type: " + lowestPrice.getType());
System.out.println("Make: " + lowestPrice.getMake());
System.out.println("Model: " + lowestPrice.getModel());
System.out.println("Price: " + lowestPrice.getPrice());
System.out.println("No of Doors: " + lowestPrice.getDoors() + "\n");
}
public Cars(String type, String make, String model, int price, int Doors){
Type = type;
Make = make;
Model = model;
Price = price;
NoDoors = Doors;
}
public String getType(){
return Type;
}
public String getMake(){
return Make;
}
public String getModel(){
return Model;
}
public int getPrice(){
return Price;
}
public int getDoors(){
return NoDoors;
}
}
我被告知,除了做一个get方法,我也必须使用set方法。但是如果没有set方法,我的程序仍然有效。我只是想知道set方法是否重要
答案 0 :(得分:2)
你不应该只是添加东西,因为有人告诉你;你应该在他们需要的时候添加它们。
由于您的代码现在正好,它只是通过构造函数构造您的Cars
(请记住,对象通常是单数,而不是复数)对象。如果您从未希望能够在创建汽车后更改汽车的属性,那么您可以保持原样。
setter用于提供对支持字段的操作访问。如果您不需要或不想要这个,那么您就不应该添加它。
旁注:添加它可能仍然是个好主意,但要改为private
。如果你想要验证逻辑(例如检查价格不是负数),那么这应该通过一个setter来完成。