我对 Java 相当陌生,我已经用尽了所有当前资源来寻找答案。我想知道是否可以访问对象第一个属性来查看它是否与特定整数匹配?
例如,我尝试通过产品 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;
}
}
请告诉我
最佳答案
您已经获得了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
。您不需要那里的包装类型。
关于java - 如何比较ArrayList中的对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18408850/