How to compare Objects attributes in an ArrayList?

2020-02-16 02:38发布

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 matches a particular integer?

For example, I am trying to obtain a Product that is within my Database by searching for it by it's Product ID. Therefore, if I create two products such as, Product ipad = new Product(12345, "iPad", 125.0, DeptCode.COMPUTER); and Product ipod = new Product(12356, "iPod", 125.0, DeptCode.ELECTRONICS); (I have included this Product class below), and add them to an Arraylist such as, List<Product> products = new ArrayList<Product>(); how can I loop through this ArrayList in order to find that product by its ID? This is the method I am working on:

List<Product> products = new ArrayList<Product>();


@Override
public Product getProduct(int productId) {
    // TODO Auto-generated method stub
    for(int i=0; i<products.size(); i++){
        //if statement would go here
        //I was trying: if (Product.getId() == productId) {
        System.out.println(products.get(i));
    }
    return null;
}`

I know that I can include a conditional statement in the for loop but I cant figure out how to access the getId() method in the Product class to compare it the productId parameter?

 package productdb;

public class Product {
    private Integer id;
    private String name;
    private double price;
    private DeptCode dept;

    public Product(String name, double price, DeptCode code) {
        this(null, name, price, code);
    }

    public Product(Integer id, String name, double price, DeptCode code) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.dept = code;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    public Integer getId() {
        return id;
    }


    public void setId(Integer id) {
        this.id = id;
    }

    public DeptCode getDept() {
        return dept;
    }

    public void setDept(DeptCode dept) {
        this.dept = dept;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        String info = String.format("Product [productId:%d,  name: %s, dept: %s, price: %.2f",
                id, name, dept, price);
        return info;
    }

}

Please let me know

4条回答
放我归山
2楼-- · 2020-02-16 02:42

For comparing the ArrayList Objects make override equal function in your CustomObject Class Like Employee.

ArrayList<Employee> list;
Employee emp; 
//suppose you have some number of items in that list and emp object contains some value.
int size=list.size();  
for(int i=0;i<size;i++) {
    if(list.get(i).equals(emp)) {
        //todo perform operation on the basis of result.
    }
}

And suppose this is your Employee class and in that class you need to override the equal function.

class Employee{
    int age;
    String name;

    public int getAge() {
        return this.age;
    }

    public String getName() {
        return this.name;
    }

    public void setAge(int emp_age) {
        this.age=emp_age;
    }

    public void setName(String emp_name) {
        this.name=emp_name;
    }

    @Override
    public boolean equal(Employee emp) {
        boolean isEqual=false;
        if(emp!=null && emp instanceof Employee) {
            isEqual=(this.age==emp.age);
        }
        return isEqual;
    }



}

I hope this solution will help you to check for equal values and compare the values.

Thanks

查看更多
Anthone
3楼-- · 2020-02-16 02:43

According to your commented line //I was trying: if (Product.getId() == productId) I think where you were falling over is using Product (capital P). What you needed was:

if (products.get(i).getId() == productId)

Also, you weren't returning the product you found...

The problem with that form is that a) you have to find the product in the list twice (once in the condition and then again when printing the result - a third time if you returned the product) and b) it will throw a null pointer exception if the product you are looking for is not in the list.

This is a nicer, more compact way of doing it:

@Override
public Product getProduct(int productId)
{
  for(Product product : products)
  {
    if (productId == product.getId())
    {
      System.out.println(product.toString());
      return product;
    } 
  }
  return null;
}
查看更多
smile是对你的礼貌
4楼-- · 2020-02-16 02:44

You have already got the Product out of the List<Product> 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.

查看更多
乱世女痞
5楼-- · 2020-02-16 02:57

Have you considered using a HashMap (or LinkedHashMap) instead of an Array. This way you can use the productId as the key and the product as the value?

This will let you get the object without having to loop through the entire array.

查看更多
登录 后发表回答