使用增强的For循环在ArrayList中打印对象时遇到问题

时间:2019-04-16 14:23:27

标签: java object arraylist

我无法使用增强型for循环使产品对象打印出任何内容。一切都为空或0?

输出显示此内容?

0null0.0This is the id
0null0.0This is the id
0null0.0This is the id

这是我的代码:

class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
        ArrayList < Product > store1 = new ArrayList < Product > ();
        store1.add(new Product(3, "Nike", 300.0));
        store1.add(new Product(2, "Addidas", 400.0));
        store1.add(new Product(6, "Under Armor", 500.0));
        for (Product y: store1) {
            System.out.println(y + "This is the id");
        }
    }
}

class Product {
    public int id;
    public String name;
    public double price;
    public Product(int startId, String startName, double startPrice) {
        startId = id;
        startName = name;
        startPrice = price;
    }
    public int getId() {
        return id;
    }
    public double getPrice() {
        return price;
    }
    public String getName() {
        return name;
    }
    public String toString() {
        return id + name + price;
    }
}

3 个答案:

答案 0 :(得分:2)

您正在构造函数中进行向后分配:

public Product(int startId, String startName, double startPrice) {
        startId = id;
        startName = name;
        price = startPrice;
    }

不初始化对象...

但是你可以肯定

public Product(int startId, String startName, double startPrice) {
        id = startId;
        name = startName;
        startPrice = price;
    }

答案 1 :(得分:1)

您可以在构造函数中向后分配分配。应该是:

public Product(int startId, String startName, double startPrice) {
    id = startId;       // Not `startId = id;`
    name = startName;   // Not `startName = name;`
    price = startPrice; // Not `price = startPrice;`
}

或者更好的选择(这将在您尝试编译时为您提出问题),请不要依赖隐式this

public Product(int startId, String startName, double startPrice) {
    this.id = startId;
    this.name = startName;
    this.price = startPrice;
}

答案 2 :(得分:0)

您在构造函数中错误地设置了变量,即

startId = id;应该是id = startId;

您还应该将@Override添加到toString()方法中。