如何为实例设置唯一ID

how to set unique ID to instances

我正在尝试创建具有唯一标识符 (ID) 的 class product 实例。

ID 就像商店中产品的条形码一样,用户可以在添加产品后更改 ID。

这是我目前拥有的:

public class Product {

    private int id;
    //and some other attributes...

    public Product (int id){
        this.id = id;
    }


    public void setId(){
        this.Id = id;
    }

    //more not relevant methods...
    }

我正在考虑创建一个 class 来包含所有创建的产品,如下所示:

public class Inventory{

    ArrayList<Product> products;
    //not sure if I should use product array or ID's array

    public Producto createProduct(int id){
        if (products.contains(/* product with id*/)){
            // not sure what to use here
        }
        else{
          return new Producto(id);
        }
    }

}

所以我不确定如何让它发挥作用,或者 class Inventory 是否是个好主意。

您可以修改 Inventory class 以包含如下数据结构

HashMap<Integer, Product> products;

在构造函数中初始化,然后就可以调用products.contains(<int id>)。您需要相应地向此数据结构添加新产品。

为了正确有效地使用 HashMap,您还需要阅读有关覆盖 equals()hashcode() 方法的内容。 HashMap 给你 O(1) 插入和 O(1) 查找。