java 将元素添加到 arraylist 并测试该数字是否已存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6730745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:03:21  来源:igfitidea点击:

Add element to arraylist and test if the number already exist

javaarraylist

提问by radder

I have a method which add element to an arraylist My task is to Modify the addProduct method so that a new product cannot be added to the product list with the same ID as an existing one.

我有一个将元素添加到数组列表的方法 我的任务是修改 addProduct 方法,以便无法将新产品添加到与现有产品具有相同 ID 的产品列表中。

Since both number and string are in the same word "item" and stored on the same index, I don't know how I can just get the number. I need the number to test to see if the number already exist

由于数字和字符串都在同一个词“项目”中并存储在同一个索引中,我不知道如何才能获得数字。我需要这个号码来测试看看这个号码是否已经存在

Any suggestion on how I should do this?

关于我应该如何做到这一点的任何建议?

The way I add to the arraylist is like this below:

我添加到数组列表的方式如下:

(new Product(132, "Clock Radio"))

public void addProduct(Product item)
{
 stock.add(item);
 }

回答by sgokhales

I would greatly recommend you to go for Setinside the addProduct()method.

我强烈建议您使用SetaddProduct()方法。

From the Javadocs,

从 Javadocs,

SET
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.

SET
不包含重复元素的集合。更正式地说,集合不包含一对元素 e1 和 e2,使得 e1.equals(e2),并且最多包含一个空元素。

Implement like this,

像这样实施,

public static boolean checkDuplicate(ArrayList list) {
 HashSet set = new HashSet();
 for (int i = 0; i < list.size(); i++) {
  boolean val = set.add(list.get(i));
  if (val == false) {
    return val;
  }
 }
 return true;
}

回答by Thilo

public void addProduct(Product item){
   for (Product p: stock)
      if (p.getId() == item.getId())
         return;
   stock.add(item);
}

回答by spot35

I would use a java.util.Set. You would need to implement the equals() and hashcode() methods of the Product class based on the two fields passed into the constructor.

我会使用 java.util.Set。您需要根据传递给构造函数的两个字段来实现 Product 类的 equals() 和 hashcode() 方法。

回答by Michele

Try using a HashMap with the ID as the Key and the Item as the Value. In an HashMap you cant duplicate Items with the same Key, so your problem is solved at the bottom of your programming. :)

尝试使用一个 HashMap,以 ID 作为键,以 Item 作为值。在 HashMap 中,您不能使用相同的 Key 复制 Items,因此您的问题在编程的底部得到解决。:)

回答by rtheunissen

Create a ProductList class that has an ArrayList field and a integer set to keep track of ID's that have been added. When you add an item, check if the set already contains the item's ID. If it doesn't, add the item to the ArrayList. So this basically wraps around an ArrayList quite nicely. Here's how I would do it:

创建一个 ProductList 类,该类具有一个 ArrayList 字段和一个整数集,以跟踪已添加的 ID。添加项目时,请检查该集合是否已包含该项目的 ID。如果没有,则将该项目添加到 ArrayList。所以这基本上很好地环绕了一个 ArrayList。这是我将如何做到的:

public class ProductList{
...
    private ArrayList<Product> list = new ArrayList<Product>();
    private Set<Integer> ids = new Set<Integer>();
...
    public void addProduct(Product product){
       if(!ids.contains(product.getID())){
            list.add(product);
            ids.add(product.getID());
           }
         }

    public Product removeProduct(Product product){
       if(!list.contains(product)) return null;
       ids.remove(product.getID());
       return list.remove(product);
      }
...
    }

You can then just use

然后你可以使用

ProductList stock = new ProductList();

and stock.addProduct(Product item);in your other class.

stock.addProduct(Product item);你的其他班级。

If you think you'll be using your list quite extensively, creating practical constructors to integrate with your data fields will be very useful as well.

如果您认为您将非常广泛地使用您的列表,那么创建实用的构造函数来与您的数据字段集成也将非常有用。

This is a very good approach from an abstraction point of view, however it's probably not the most efficient way of doing it.

从抽象的角度来看,这是一种非常好的方法,但它可能不是最有效的方法。