将arrayList的元素相互比较

时间:2015-06-16 14:20:32

标签: java

我有一个包含四个对象元素的数组列表,我需要将这些对象相互比较。如果两个对象相同,我需要避免类似的对象比较并继续进行。我尝试了下面的代码,但它避免了常见的对象迭代。任何人都可以建议我比较同一个数组列表中的元素的最佳方法吗?

代码:

List<Student> studentInfo= new ArrayList<Student>();

 for (int i = 0; i < list.size(); i++)
            {
                for (int j = 0 ; j < list.size(); j++)
                {


                    if(list.get(i).getstudentId().equals(list.get(j).getstudentId())) 
                    continue;

                    }

                }

            }

2 个答案:

答案 0 :(得分:2)

你需要避免i == j的情况,在这种情况下你的if会评估为真

if(i != j && list.get(i).getstudentId().equals(list.get(j).getstudentId())) 
  break;

如果你想知道循环的退出,如果你发现重复,你需要一个外部变量让你知道(比如布尔或者一个int,它将显示找到副本的位置)

答案 1 :(得分:0)

您可以使用冒泡排序算法,但不是排序,而是可以根据需要使用它。

更优雅的比较方法是:

public class Student {

    private String id;

    /**
     * @return the id
     */
    public String getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }



    @Override
    public boolean equals (Object otherObject){
        if(!(otherObject instanceof Student)){
            return false;
        }
        if(((Student)otherObject).getId().equals(this.id)){
            return true;
        }
        return false;
    }

}

在你班上:

for(int i = 0; i< studentList.size(); i++){
    for(int j = i+1; j< studentList.size(); j++){
        if(studentList.get(i).equals(studentList.get(j))){
            continue;
        }
    }
}
相关问题