关于Set的add方法
public static void main(String[] args) {
Set<Integer> set = new HashSet<>();
int[] a = {1,2,2,3,3,4,5,5};
for (int i = 0; i < 5; i++) {
if (set.add(a[i])){//添加成功
System.out.println("添加成功");
}else if (!set.add(a[i])){//添加失败
System.out.println("添加失败");
}
}
}
结果:
因为set中的元素是唯一的,所以如果添加相同的元素,则添加失败。