Home > Software engineering >  How to call get method on an Array Object - Java
How to call get method on an Array Object - Java

Time:04-26

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

    }

CodePudding user response:

The same way as it is done with arrays! Accessing using index values. Since you want to access from ArrayList use below code:

//get 0th element of cartList, which will be a SumUserCart object
SumUserCart suc = cartList.get(0);
//creating productsCarts object array:
ProductsCarts[] pc = suc.getProducts();
//Now use getProductId() method:
int pid = pc[0].getProductId(0);

CodePudding user response:

That's the right method to call this

private static void printTheCart(List<SumUserCart> cartList){
        for (SumUserCart cartsByUser : cartList) {
            System.out.println("User Id: "   cartsByUser.getUserId()   " = "   Arrays.toString(cartsByUser.getProducts()));
            ProductsCart[] pcx = cartsByUser.getProducts();
            for (ProductsCart pc : pcx)
                System.out.println(pc.getProductId());
                
        }
  • Related