Java HashSet中的问题-保存对象

Java HashSet中的问题-保存对象,java,Java,我有产品列表。该列表包含文本框中的复选框和数量。如果用户选择的特定产品需要将该对象保存在哈希集中 CheckBox Name Price Qty [] Pen 21 TextBox [] aaa 11 TextBox [] bbb 25 TextBox 当用户选中复选框时,将该对象保存到HashSet中 Set<Product> s = new HashSet<Produc

我有产品列表。该列表包含文本框中的复选框和数量。如果用户选择的特定产品需要将该对象保存在哈希集中

 CheckBox    Name  Price   Qty
 []          Pen   21    TextBox
 []          aaa   11    TextBox
 []          bbb   25    TextBox
当用户选中复选框时,将该对象保存到HashSet中

Set<Product> s = new HashSet<Product>();
Product product = new Product();
product.setName("Pen");
product.setPrice(21.00);
product.setName(10);
//s.add(product);
 if(!s.add(product))
    System.out.println("Duplicate detected : " + product);
}
Set s=newhashset();
产品=新产品();
product.setName(“Pen”);
产品设定价格(21.00);
产品名称(10);
//s、 添加(产品);
如果(!s.add(产品))
System.out.println(“检测到重复:+产品”);
}
问题是:

我选择了一个特定的产品。一段时间后,我正在更改该已保存产品的数量。 我们如何做到这一点:

如何获取保存的对象并更改某些属性并将其保存回

请帮帮我


提前感谢。

您可以向
产品
类添加几个方法:

public class Product {

    String name;
    double price;
    int quantity;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    @Override
    public String toString() {
        return "Product [name=" + name + ", price=" + price + ", quantity="
                + quantity + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        long temp;
        temp = Double.doubleToLongBits(price);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Product other = (Product) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (Double.doubleToLongBits(price) != Double
                .doubleToLongBits(other.price))
            return false;
        return true;
    }

}
  • public int getQuantity()
  • void setQuantity(整数数量)
但是,您不应该修改
哈希集中的对象:删除它并添加新对象更安全。事实上,如果您修改
哈希集中的对象,您将修改其哈希值

下面是一些代码:

public class Main {

    public static void main(String[] args) {
        new Main().go();
    }

    public void go() {
        Product p1 = new Product();
        p1.setName("P1");
        p1.setPrice(2.5);
        p1.setQuantity(1);

        Product p2 = new Product();
        p2.setName("P2");
        p2.setPrice(5.3);
        p2.setQuantity(1);

        Set<Product> products = new HashSet<Product>();
        products.add(p1);
        products.add(p2);

        System.out.println(products);

        // now let's assume that you want to change quantity of P1

        Product newp1 = new Product();
        newp1.setName("P1");
        newp1.setPrice(2.5);
        newp1.setQuantity(2);

        if (products.contains(newp1)) {
            products.remove(newp1);
        }
        products.add(newp1);

        System.out.println("after update:");
        System.out.println(products);
    }

}

请注意,我已经覆盖了
hashCode
equals
,而没有考虑字段
数量
。更好的选择是有两个类:
Product
只包含
name
price
,以及
ProductOrder
两个字段:A
Product
和A
quantity
您可以向
Product
类添加两个方法:

public class Product {

    String name;
    double price;
    int quantity;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    @Override
    public String toString() {
        return "Product [name=" + name + ", price=" + price + ", quantity="
                + quantity + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        long temp;
        temp = Double.doubleToLongBits(price);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Product other = (Product) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (Double.doubleToLongBits(price) != Double
                .doubleToLongBits(other.price))
            return false;
        return true;
    }

}
  • public int getQuantity()
  • void setQuantity(整数数量)
但是,您不应该修改
哈希集中的对象:删除它并添加新对象更安全。事实上,如果您修改
哈希集中的对象,您将修改其哈希值

下面是一些代码:

public class Main {

    public static void main(String[] args) {
        new Main().go();
    }

    public void go() {
        Product p1 = new Product();
        p1.setName("P1");
        p1.setPrice(2.5);
        p1.setQuantity(1);

        Product p2 = new Product();
        p2.setName("P2");
        p2.setPrice(5.3);
        p2.setQuantity(1);

        Set<Product> products = new HashSet<Product>();
        products.add(p1);
        products.add(p2);

        System.out.println(products);

        // now let's assume that you want to change quantity of P1

        Product newp1 = new Product();
        newp1.setName("P1");
        newp1.setPrice(2.5);
        newp1.setQuantity(2);

        if (products.contains(newp1)) {
            products.remove(newp1);
        }
        products.add(newp1);

        System.out.println("after update:");
        System.out.println(products);
    }

}

请注意,我已经覆盖了
hashCode
equals
,而没有考虑字段
数量
。更好的选择是有两个类:
Product
只包含
name
price
,以及
ProductOrder
两个字段:A
Product
和A
quantity
只要从集合中获取对对象的引用,使用对象公开的方法修改其值,下一次检索将为您提供更新的对象。 如果您已经重写了产品类的equals()和hashcode()方法,您还可以发布它们吗

比如说:

//set.add(savedProduct);
//savedProduct.setQuantity(newQuantity);
//now the product saved in the set has the new quantity.

因此,您无需将任何内容保存回,只需获取对对象的引用并使用引用修改对象。

只需从集合中获取对对象的引用,使用对象公开的方法修改其值,下次检索将为您提供更新的对象。 如果您已经重写了产品类的equals()和hashcode()方法,您还可以发布它们吗

比如说:

//set.add(savedProduct);
//savedProduct.setQuantity(newQuantity);
//now the product saved in the set has the new quantity.
因此,您不需要再保存任何内容,只需获取对对象的引用并使用该引用修改对象。

由于没有任何getter方法,因此您必须获取迭代器,然后在集合上进行迭代,直到找到要查找的迭代器,更改它,然后添加

因此,请退出迭代器,然后:

Product p;
while(itr.hasNext()){
    p = itr.next();
    if(p.equals(name) {
        itr.remove();
        //do stuff to it;
        s.add(p);
        break;
    }
}
如果您没有找到它,请进行一些清理,等等。

因为没有任何getter方法,您必须获取迭代器,然后在集合上迭代,直到找到您要查找的迭代器,更改它,然后添加

因此,请退出迭代器,然后:

Product p;
while(itr.hasNext()){
    p = itr.next();
    if(p.equals(name) {
        itr.remove();
        //do stuff to it;
        s.add(p);
        break;
    }
}

如果您没有找到它,请进行一些清理等。

在使用Set接口时,直接的方法是编写一个搜索方法,该方法迭代集合的所有元素,并搜索给定的产品名称,例如“Pen”。然后您可以设置搜索产品的数量。这样,您就不必将元素放回集合。

使用集合接口时,最直接的方法是编写一个搜索方法,迭代集合中的所有元素并搜索给定的产品名称,比如“笔”。然后您可以设置搜索产品的数量。这样,您就不必将元素放回集合。

使用
映射是否更容易?您可以使用产品名称作为键,只需按名称从集合中检索产品对象

 Map<String, Product> products = new HashMap<String, Product>();

 public void addProduct(Product product){
   if(products.get(product.getName())!=null){
     products.get(product.getName()).addQuantity(product.getQuantity());
   }else{
      products.put(product.getName(), product);
   }
  }
Map products=newhashmap();
公共产品(产品){
if(products.get(product.getName())!=null){
products.get(product.getName()).addQuantity(product.getQuantity());
}否则{
products.put(product.getName(),product);
}
}

请注意,对于此解决方案,产品名称必须是唯一的。如果两个产品具有相同的名称,则除非您强制使用唯一的名称或为具有唯一性的产品添加一个字段,否则您不能使用该名称。

为此使用
映射不是更容易吗?您可以使用产品名称作为键,只需按名称从集合中检索产品对象

 Map<String, Product> products = new HashMap<String, Product>();

 public void addProduct(Product product){
   if(products.get(product.getName())!=null){
     products.get(product.getName()).addQuantity(product.getQuantity());
   }else{
      products.put(product.getName(), product);
   }
  }
Map products=newhashmap();
公共产品(产品){
if(products.get(product.getName())!=null){
products.get(product.getName()).addQuantity(product.getQuantity());
}否则{
products.put(product.getName(),product);
}
}

请注意,对于此解决方案,产品名称必须是唯一的。如果两个产品具有相同的名称,则您不能使用此名称,除非您强制使用唯一的名称或为具有唯一性的产品添加字段

我添加了这些setter&getter。例如,在我设置product.setQty(10.00)setInstance.addd(产品)之前;在那之后,我想再拿一次那个对象并改变它并保存它。。。如何做?不要做:从集合中删除旧对象并添加新对象。这更安全,因为如果更改集合中的对象,则会更改其哈希代码!我添加了这些setter和getter