如何在数组对象上调用获取方法-Java
我有2个类,在Sumusercart中,我初始化对象的数组,然后我必须在Productcart中调用productid in ProductiD的方法,任何解决方案吗?
数据位于列表
List<SumUserCart> cartList
Sumusercart类中:
public class SumUserCart {
int userId;
ProductsCart[] products;
public SumUserCart(int userId, ProductsCart[] products) {
this.userId = userId;
this.products = products;
}
@Override
public String toString() {
return "SumUserCart{" +
"userId=" + userId +
", products=" + Arrays.toString(products) +
'}';
}
public ProductsCart[] getProducts() {
return products;
}
//getters & setters here
}
Productcart类:
public class ProductsCart {
int productId;
int quantity;
@Override
public String toString() {
return "ProductsCart{" +
"productId=" + productId +
", quantity=" + quantity +
'}';
}
public ProductsCart() {}
public ProductsCart(int productId, int quantity) {
this.productId = productId;
this.quantity = quantity;
}
//getters & setters here
}
这是我的功能,我试图打印产品ID的位置:
private static void printTheCart(List<SumUserCart> cartList){
for (SumUserCart cartsByUser : cartList) {
System.out.println("User Id: " + cartsByUser.getUserId() + " = " + Arrays.toString(cartsByUser.getProducts()));
//System.out.println(cartsByUser.getProducts());
}
}
I have 2 classes, in SumUserCart i initialize the array of object, then i have to call get method on productID in ProductCart, any solutions?
The data is in list
List<SumUserCart> cartList
SumUserCart class:
public class SumUserCart {
int userId;
ProductsCart[] products;
public SumUserCart(int userId, ProductsCart[] products) {
this.userId = userId;
this.products = products;
}
@Override
public String toString() {
return "SumUserCart{" +
"userId=" + userId +
", products=" + Arrays.toString(products) +
'}';
}
public ProductsCart[] getProducts() {
return products;
}
//getters & setters here
}
ProductCart class:
public class ProductsCart {
int productId;
int quantity;
@Override
public String toString() {
return "ProductsCart{" +
"productId=" + productId +
", quantity=" + quantity +
'}';
}
public ProductsCart() {}
public ProductsCart(int productId, int quantity) {
this.productId = productId;
this.quantity = quantity;
}
//getters & setters here
}
That's my function, where i am trying to print the product id's:
private static void printTheCart(List<SumUserCart> cartList){
for (SumUserCart cartsByUser : cartList) {
System.out.println("User Id: " + cartsByUser.getUserId() + " = " + Arrays.toString(cartsByUser.getProducts()));
//System.out.println(cartsByUser.getProducts());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与数组的方式一样!使用索引值访问。
由于您想从ArrayList访问以下代码:
The same way as it is done with arrays! Accessing using index values.
Since you want to access from ArrayList use below code:
那是称呼这个的正确方法
That's the right method to call this