【发布时间】:2017-06-02 22:46:08
【问题描述】:
我是初学者,想知道如何使用循环来更新对象 ArrayList 中的属性。所以这里我有一个智能手机的arraylist,每个智能手机都有serialNo和brand作为属性,但价格还没有更新。
public class Smartphone{
public String serialNo;
public String brand;
public Double price;
public Smartphone(String serialNo, String brand){
this.serialNo = serialNo;
this.brand = brand;
}
public void setPrice(double price){
this.price = price;
}
}
public class Test{
public static void main(String[] args) throws Exception{
ArrayList<Smartphone> smartphones = new ArrayList<Smartphone>();
for (int i = 0; i < 5; i++){
Smartphone s = new Smartphone("12345678" ,"Samsung");
smartphones.add(s);
}
//later I realize I want to add the price,
//but it seems the loop I'm using is not working
for (int i = 0; i < 5; i++){
smartphones.get(i).setPrice(398);
}
}
}
我想知道为什么我使用的循环不起作用,有没有其他方法可以为每部智能手机增加价格?
【问题讨论】:
-
不工作是什么意思?我的意思是你怎么知道这不起作用。
-
您的价格设置有效,如果您开始打印价格,您会看到它正在为列表中的每部智能手机打印正确的值
-
只需在
setPrice行旁边添加System.out.println(smartphones.get(i));,您可能想要覆盖Smartphone.toString()以获得有用的东西;) -
为了让它对初学者更友好,只需将它设为
System.out.println(smartphones.get(i).price); -
为什么类使用
Double包装类?