簡體   English   中英

如何比較 ArrayList 中的對象屬性?

[英]How to compare Objects attributes in an ArrayList?

我對 Java 相當陌生,我已經用盡了我當前的所有資源來尋找答案。 我想知道是否可以訪問 Objects first 屬性以查看它是否與特定整數匹配?

例如,我試圖通過搜索它的產品 ID 來獲取我的數據庫中的產品。 因此,如果我創建兩個產品,例如Product ipad = new Product(12345, "iPad", 125.0, DeptCode.COMPUTER); and 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;
}`

我知道我可以在 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;
    }

}

請告訴我

你已經拿到了Product出的List<Product>在下面的語句:

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

現在,您有了Product ,現在要獲取它的id ,您可以調用它的getId()方法:

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

我還建議您使用增強的 for 循環而不是像這樣的傳統循環:

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

此外,您應該將productId的類型從Integer更改為int 您在那里不需要包裝器類型。

您是否考慮過使用 HashMap(或 LinkedHashMap)而不是 Array。 這樣您就可以使用 productId 作為鍵,使用 product 作為值嗎?

這將使您無需遍歷整個數組即可獲取對象。

根據您的評論行//I was trying: if (Product.getId() == productId)我認為您摔倒的地方是使用Product (大寫P)。 你需要的是:

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

此外,您沒有退回您找到的產品......

該表單的問題在於 a) 您必須在列表中找到產品兩次(一次在條件中,然后在打印結果時再次查找 - 如果您返回產品,則第三次)並且 b) 它會拋出一個空指針如果您要查找的產品不在列表中,則例外。

這是一種更好、更緊湊的方法:

@Override
public Product getProduct(int productId)
{
  for(Product product : products)
  {
    if (productId == product.getId())
    {
      System.out.println(product.toString());
      return product;
    } 
  }
  return null;
}

為了比較 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.
    }
}

假設這是您的 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;
    }



}

我希望這個解決方案能幫助您檢查相等的值並比較這些值。

謝謝

這真的幫助了我,感謝代碼的工作10/10

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM