我对Java相当陌生,而且我已经耗尽了所有当前资源以找到答案。我想知道是否有可能访问一个对象的第一个属性,看看它是否匹配一个特定的整数?如何比较ArrayList中的对象属性?
例如,我试图通过按产品ID搜索产品来获得位于我的数据库中的产品。因此,如果我创建了两个产品,例如Product ipad = new Product(12345, "iPad", 125.0, DeptCode.COMPUTER);
和Product ipod = new Product(12356, "iPod", 125.0, DeptCode.ELECTRONICS);
(我已在下面包括此产品类别),并将它们添加到诸如List<Product> products = new ArrayList<Product>();
之类的Arraylist,如何通过此ArrayList循环以便通过其ID找到该产品? 这是我的工作方法:我知道我可以包括在for循环条件语句,但我无法弄清楚如何访问getId()方法在产品类比较它
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;
}`
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;
}
}
请让我知道
==比较的引用不上的对象的值和整数是一个对象 –
@YasirShabbirChoudhary由于'productId'参数的方法是一种原始'int'类型,'product.getId()'将被解包,以在比较完成之前'int'。 –