How to compare Objects attributes in an ArrayList?

后端 未结 4 893
故里飘歌
故里飘歌 2020-12-22 09:57

I am fairly new to Java and I have exhausted all of my current resources to find an answer. I am wondering if it possible to access an Objects first property to see if it ma

4条回答
  •  清歌不尽
    2020-12-22 10:37

    You have already got the Product out of the List in the following statement:

    System.out.println(products.get(i));
    

    Now, that you have got Product, now to get it's id, you can just call it's getId() method:

    if (product.get(i).getId() == productId) {
        // Return this product.
    }
    

    I would also suggest you to use enhanced for-loop instead of the traditional loop like this:

    for (Product product: products) {
        // Now you have the product. Just get the Id
        if (product.getId() == productId) {
            return product;
        }
    }
    

    Also, you should change the type of productId from Integer to int. You don't need a wrapper type there.

提交回复
热议问题