Java:如何检测ArrayList中的重复项?

121

如何在Java中检测(返回true/false)一个ArrayList是否包含多个相同的元素?

非常感谢, Terry

编辑 忘记提到我不想将“块”与彼此进行比较,而是比较它们的整数值。 每个“块”都有一个int,这就是它们的不同之处。 通过调用名为“getNum”的方法(例如table1 [0] [2] .getNum();)可以找到特定块的int。


如果“Block”是由int进行比较的,那么hashCode应该返回相同的int,并且equals应该比较这些int。 - Paul Tomblin
使用Set而不是List - dmarquina
17个回答

1

这个答案是用Kotlin编写的,但很容易转换为Java。

如果您的ArrayList大小在一个固定的小范围内,则这是一个很好的解决方案。

var duplicateDetected = false
    if(arrList.size > 1){
        for(i in 0 until arrList.size){
            for(j in 0 until arrList.size){
                if(i != j && arrList.get(i) == arrList.get(j)){
                    duplicateDetected = true
                }
            }
        }
    }

1
简单来说: 1)确保所有项目可比较 2)对数组进行排序 3)遍历数组并查找重复项

考虑到算法复杂度,这太贵了。最好的排序是O(n*log(n)),而你可以用O(n)的复杂度找到重复项。 - Sergiy Dakhniy

1
private boolean isDuplicate() {
    for (int i = 0; i < arrayList.size(); i++) {
        for (int j = i + 1; j < arrayList.size(); j++) {
            if (arrayList.get(i).getName().trim().equalsIgnoreCase(arrayList.get(j).getName().trim())) {
                return true;
            }
        }
    }

    return false;
}

0
    ArrayList<String> withDuplicates = new ArrayList<>();
    withDuplicates.add("1");
    withDuplicates.add("2");
    withDuplicates.add("1");
    withDuplicates.add("3");
    HashSet<String> set = new HashSet<>(withDuplicates);
    ArrayList<String> withoutDupicates = new ArrayList<>(set);

    ArrayList<String> duplicates = new ArrayList<String>();

    Iterator<String> dupIter = withDuplicates.iterator();
    while(dupIter.hasNext())
    {
    String dupWord = dupIter.next();
    if(withDuplicates.contains(dupWord))
    {
        duplicates.add(dupWord);
    }else{
        withoutDupicates.add(dupWord);
    }
    }
  System.out.println(duplicates);
  System.out.println(withoutDupicates);

为当前问题提供帮助的答案需要加上一些说明,以便更好地解释。 - ρяσѕρєя K

0
/**
     * Method to detect presence of duplicates in a generic list. 
     * Depends on the equals method of the concrete type. make sure to override it as required.
     */
    public static <T> boolean hasDuplicates(List<T> list){
        int count = list.size();
        T t1,t2;

        for(int i=0;i<count;i++){
            t1 = list.get(i);
            for(int j=i+1;j<count;j++){
                t2 = list.get(j);
                if(t2.equals(t1)){
                    return true;
                }
            }
        }
        return false;
    }

一个重写了 equals() 方法的具体类的示例:
public class Reminder{
    private long id;
    private int hour;
    private int minute;

    public Reminder(long id, int hour, int minute){
        this.id = id;
        this.hour = hour;
        this.minute = minute;
    }

    @Override
    public boolean equals(Object other){
        if(other == null) return false;
        if(this.getClass() != other.getClass()) return false;
        Reminder otherReminder = (Reminder) other;
        if(this.hour != otherReminder.hour) return false;
        if(this.minute != otherReminder.minute) return false;

        return true;
    }
}

0
    String tempVal = null;
    for (int i = 0; i < l.size(); i++) {
        tempVal = l.get(i); //take the ith object out of list
        while (l.contains(tempVal)) {
            l.remove(tempVal); //remove all matching entries
        }
        l.add(tempVal); //at last add one entry
    }

注意:尽管从列表开头删除项目会对性能产生重大影响。 为了解决这个问题,我们有两个选择。1)以相反的顺序迭代并删除元素。2)使用LinkedList而不是ArrayList。由于在面试中问的偏见问题要求从List中删除重复项而不使用任何其他集合,上面的例子就是答案。但在现实世界中,如果我必须实现这一点,我会将List中的元素放入Set中,简单!

-1
一个适合初学者的简单解决方案。 //查找重复项的方法。
public static List<Integer> findDublicate(List<Integer> numList){
    List<Integer> dupLst = new ArrayList<Integer>();
    //Compare one number against all the other number except the self.
    for(int i =0;i<numList.size();i++) {
        for(int j=0 ; j<numList.size();j++) {
            if(i!=j && numList.get(i)==numList.get(j)) {
                boolean isNumExist = false;
                //The below for loop is used for avoid the duplicate again in the result list
                for(Integer aNum: dupLst) {
                    if(aNum==numList.get(i)) {
                        isNumExist = true;
                        break;
                    }
                }
                if(!isNumExist) {
                    dupLst.add(numList.get(i));
                }
            }
        }
    }
    return dupLst;
}

基本上是 这个答案 的复制,加上使用结果列表和手动检查重复项的额外低效性,以及错误的对象比较。 - shmosel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接