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;
}
答案 0 :(得分:0)
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。