我对 Java 还很陌生,我已经用尽所有当前资源来寻找答案。我想知道是否可以访问 Objects first 属性以查看它是否与特定整数匹配?
例如,我试图通过按产品 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;
}`
我知道我可以在 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;
}
}
请告诉我