添加元素ArrayList和测试,如果数量已经存在 [英] Add element to arraylist and test if the number already exist

查看:96
本文介绍了添加元素ArrayList和测试,如果数量已经存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元素添加到一个ArrayList的方法
我的任务是修改addProduct命令的方法,使新产品
不能被添加到产品列表具有相同ID
作为现有之一。

由于这两个数字和字符串都在同一个词项,并存储在相同的指数,我不知道我怎么能刚刚获得的数量。我需要的数量来测试以查看是否号码已存在

这是我应该怎么做任何建议?

我添加到ArrayList的方法是这样如下:

 (新产品(132,时钟收音机))公共无效addProduct命令(产品项)
{
 stock.add(项目);
 }


解决方案

我会大大推荐你去的 设置 addProduct命令()方法内。

从Javadoc文档,


  

SET 结果
  不包含重复元素的集合。更正式地,集合
  不包含对E1和e2元素使得e1.equals(E2)中,在
  最多有一个null元素。


实施这样的,

 公共静态布尔checkDuplicate(ArrayList的列表){
 HashSet的设置=新的HashSet();
 的for(int i = 0; I<则为list.size();我++){
  布尔VAL = set.add(list.get(I));
  如果(VAL == FALSE){
    返回VAL;
  }
 }
 返回true;
}

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?

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

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

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

解决方案

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

From the 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.

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

这篇关于添加元素ArrayList和测试,如果数量已经存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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