java - 使用增强的 For 循环在 ArrayList 中打印对象时出现问题

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

最佳答案

您正在构造函数中进行向后赋值:

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

关于java - 使用增强的 For 循环在 ArrayList 中打印对象时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55710474/

相关文章:

java - 定义了 equals 和 hashCode,arrayList 方法仍然不起作用

java - 图像存储即服务

python - 为什么分配给类属性的函数被视为实例方法?

javascript - 获取 2014 年特定月份的正确天数 javascript

c++ - 使用单例类从所有类到达

Java subList ConcurrentModificationException();

java - 禁止默认 Servlet 写入权限

java - 如何将 "MM-dd-yyyy hh:mm"字符串日期格式转换为 GMT 格式?

java - 为什么 Java 使用 'equals' 而不是 '==' 来检查对象在 Map 中的存在?

java - for循环迭代错误地填充数组列表