首页 > 解决方案 > 使用增强型 For 循环在 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;
    }
}

标签: javaobjectarraylist

解决方案


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

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;
    }

推荐阅读