Java 如何比较 ArrayList 中的对象属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18408850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:22:06  来源:igfitidea点击:

How to compare Objects attributes in an ArrayList?

javadatabasearraylist

提问by Brandon

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?

我对 Java 相当陌生,我已经用尽了我当前的所有资源来寻找答案。我想知道是否可以访问 Objects first 属性以查看它是否与特定整数匹配?

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:

例如,我试图通过搜索它的产品 ID 来获取我的数据库中的产品。因此,如果我创建两个产品,例如,Product ipad = new Product(12345, "iPad", 125.0, DeptCode.COMPUTER);Product ipod = new Product(12356, "iPod", 125.0, DeptCode.ELECTRONICS);(我在下面包含了这个 Product 类),并将它们添加到一个 Arraylist 中,例如,List<Product> products = new ArrayList<Product>();我如何遍历这个 ArrayList 以便通过其 ID 找到该产品?这是我正在研究的方法:

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?

我知道我可以在 for 循环中包含条件语句,但我无法弄清楚如何访问 Product 类中的 getId() 方法以将其与 productId 参数进行比较?

 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

请告诉我

采纳答案by Rohit Jain

You have already got the Productout of the List<Product>in the following statement:

您已经Product了解List<Product>了以下语句中的内容:

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:

现在,你已经得到了Product,现在要得到它的id,你可以调用它的getId()方法:

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 循环而不是像这样的传统循环:

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 productIdfrom Integerto int. You don't need a wrapper type there.

此外,您应该将productId的类型从更改Integerint。您在那里不需要包装器类型。

回答by KidTempo

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:

根据您的评论,//I was trying: if (Product.getId() == productId)我认为您摔倒的地方正在使用Product(大写 P)。你需要的是:

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

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.

该表单的问题在于 a) 您必须在列表中找到产品两次(一次在条件中,然后在打印结果时再次查找 - 如果您返回产品,则第三次)并且 b) 它会抛出一个空指针如果您要查找的产品不在列表中,则例外。

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

回答by itsNotABlanket

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?

您是否考虑过使用 HashMap(或 LinkedHashMap)而不是 Array。这样您就可以使用 productId 作为键,使用 product 作为值吗?

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

这将使您无需遍历整个数组即可获取对象。

回答by Aman Goyal

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

为了比较 ArrayList 对象,请在您的 CustomObject 类(如 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.

假设这是您的 Employee 类,并且在该类中您需要覆盖 equal 函数。

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

谢谢