java - 使用增强型 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;
}
}
解决方案
您正在构造函数中进行反向分配:
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;
}
推荐阅读
- dart - `toString` 方法将 null 添加到 Dart 中的对象
- bootstrap-4 - 在select2之外的mouseup上关闭引导模式
- wordpress - 请问我可以帮助我理解 Core Web Vitals CLS 吗?
- javascript - 在带有虚线圆的径向渐变的CSS背景图像中,是否可以隐藏边缘的点?
- http - 我可以从邮递员的 8080 端口捕获 HTTP 请求吗?
- javascript - 单击时使 jQuery 数据表行成为 asp-action 链接
- c# - Visual Studio Nuget 更新 - 拒绝访问 \packages\System.Security.Cryptography.X509Certificates.4.3.2\.signature.p7s
- azure - Azure EventGrid 高级筛选 isNotNull 运算符
- javafx - 如何将 JAVAFX 模块添加到路径?
- python - Dask分布式不运行python脚本