将元素添加到 arraylist 并测试该数字是否已存在 [英] Add element to arraylist and test if the number already exist

查看:18
本文介绍了将元素添加到 arraylist 并测试该数字是否已存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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?

我添加到arraylist的方式如下:

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

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

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

推荐答案

我强烈推荐你去SetaddProduct() 方法中.

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

来自 Javadoc,

From the Javadocs,

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

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.

这样实现,

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;
}

这篇关于将元素添加到 arraylist 并测试该数字是否已存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆