这个方法checkDuplicate的含义是什么?这段代码中发生了什么?

时间:2015-07-11 14:36:18

标签: java android

public static boolean checkDuplicate(ArrayList<String> list) {

        HashSet<String> set = new HashSet<String>();
        for (int i = 0; i < list.size(); i++) {
            boolean isUnique = set.add(list.get(i));
            if (!isUnique) {
                return isUnique;
            }
        }
        return true;

    }

2 个答案:

答案 0 :(得分:0)

如果您要添加到Set的元素已存在于Set中,则

set.add将返回false(因此未添加)。如果false对于输入List的至少一个元素返回false,则您的方法返回set.add,这意味着它的名称暗示 - 检查重复项。

public static boolean checkDuplicate(ArrayList<String> list) {

    HashSet<String> set = new HashSet<String>();
    for (int i = 0; i < list.size(); i++) { // iterate over all elements of input list
        boolean isUnique = set.add(list.get(i)); // returns false if list.get(i) 
                                                 // is already in the Set
        if (!isUnique) { // returns false if a non unique element was found
            return isUnique;
        }
    }
    return true; // return true if all the elements in the input List are unique

}

答案 1 :(得分:0)

In&#39; Set&#39; interface add方法有布尔返回类型。并且Set仅包含唯一值。如果您尝试插入重复值,则返回false。