比较ArrayList(Java)中对象的变量

时间:2015-03-06 09:38:16

标签: java

我尝试搜索,但无济于事,我希望你能帮助我。

我有一个ArrayList个包含对象,它们都有4个整数变量。如果这些对象的某些变量相同,我希望我的程序抛出Exception。我将尝试用伪代码编写:

for(Object x : ArrayList)
{
    if(x.Variable == someVariables)// all the variables for the objects in the arraylist
    {
        throw exception
    }
}

这是一个新手问题,但我希望你能帮助我,谢谢。

2 个答案:

答案 0 :(得分:1)

在for循环中,如果add方法返回false,则将它们添加到集合中

for(Object x : ArraList)
{
  Set<Integer> set=new HashSet<Integer>();
  for(int i:x.getAllValues()){
      boolean status=set.add(i)
      if(status==false){
        //throw exception
      }
  }
}

在对象类中编写get value方法

只需从列表中创建一个集合并检查其长度

Set<Integer> set= new HashSet<Integer>(list);
if(set.size()!=list.size()){
//contains duplicates
}

答案 1 :(得分:1)

我建议您在班级内部实施您的Object类型的价值检查。对我来说,似乎很重要的事情&#34;就像您的Object能够对其自身的值执行有效性检查一样。我举个例子:

public class Container {

    // declaration of your four variables

    // other code, maybe getters and setters

    /**
     * Checks if all variables are pairwise inequal
     * @return true if so, false otherwise
     */
    public boolean isValid() {      
        // check vars
    }
}

这样,检查列表中所有对象的例程非常简单:

for (Container x : arrayList) {
    if (!x.isValid()) {
        throw new RuntimeException("A bad thing just happend!");
    }
}