我怎样才能使Java看previous值在ArrayList和如果是一样的下一返回一个错误? [英] How can I make java look at the previous value in an arrayList and return an error if it is the same as the next?

查看:897
本文介绍了我怎样才能使Java看previous值在ArrayList和如果是一样的下一返回一个错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个创建了一个ArrayList中,做一个getter类,并取得了一种方法,是我想要做的方法是执行2错误检查......如果值为用户要添加已添加之前它会给一个错误。

I have a created a arrayList, made a getter class, and have made a method, in the method what I want to do is perform 2 error checks... 1 if the value user is going to add has already been added just before it will give an error.

说,例如,在列表中有苹果,香蕉....如果用户尝试添加香蕉再次它应该给一个错误。

say for example, in the list there is apple, banana .... if the user tries to add banana again it should give an error.

此外,如果列表中包含2相同的值,然后java的不应允许任何更多的类型的要加入,并应提供一个错误。

Also if the list contains 2 same values then java should not allow any more of that type to be added, and should provide an error.

感谢。

推荐答案

您可以使用ArrayList.contains(对象)的方法来检查,看看是否ArrayList包含相同的对象,但它听起来就像你要检查的类型的对象。我不会用一个ArrayList。我会用一个HashMap,为每个类型的按键,然后检查,看看是否HashMap具有使用HashMap.hasKey()方法的条目。如果你绝对必须使用ArrayList,你将不得不通过数组要添加的东西,并检查每一个项目每一次迭代。

You can use the ArrayList.contains(object) method to check to see if the ArrayList contains the same object, but it sounds like you want to check for type of object. I wouldn't use an ArrayList. I would use a HashMap, set the key for each type, then check to see if the HashMap has an entry using HashMap.hasKey() method. If you absolutely must use an ArrayList, you're going to have to iterate through the array each time you want to add something and check each item.

这篇关于我怎样才能使Java看previous值在ArrayList和如果是一样的下一返回一个错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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