import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> stringSet = new HashSet<>();
stringSet.add("apple");
stringSet.add("banana");
stringSet.add("orange");
stringSet.add("grape");
stringSet.add("watermelon");
String fruitToFind = "orange";
if (stringSet.contains(fruitToFind)) {
System.out.println(fruitToFind + " 存在于 HashSet。");
} else {
System.out.println(fruitToFind + " 不存在于 HashSet。");
}
String fruitToRemove = "banana";
if (stringSet.remove(fruitToRemove)) {
System.out.println(fruitToRemove + " 已从 HashSet 中移除。");
} else {
System.out.println(fruitToRemove + " 不在 HashSet 中,无需移除。");
}
System.out.println("HashSet 中的元素:");
for (String fruit : stringSet) {
System.out.println(fruit);
}
int size = stringSet.size();
System.out.println("HashSet 的大小为:" + size);
boolean isEmpty = stringSet.isEmpty();
System.out.println("HashSet 是否为空:" + isEmpty);
stringSet.clear();
System.out.println("HashSet 已清空,现在的大小为:" + stringSet.size());
}
}
- 添加元素:
boolean add(E e)
: 将指定的元素 e 添加到 HashSet 中。如果元素已经存在,则不进行添加,返回 false;否则添加成功,返回 true。
- 删除元素:
boolean remove(Object o)
: 从 HashSet 中移除指定的元素 o。如果元素存在并成功移除,则返回 true;否则,返回 false。void clear()
: 清空 HashSet 中的所有元素,使其变为空集合。
- 元素查询:
boolean contains(Object o)
: 判断 HashSet 是否包含指定的元素 o。如果包含则返回 true,否则返回 false。boolean isEmpty()
: 判断 HashSet 是否为空。如果 HashSet 中没有元素,则返回 true,否则返回 false。int size()
: 返回 HashSet 中元素的个数。
- 遍历元素:
- HashSet 是一个集合类,可以使用迭代器或者增强型 for 循环来遍历其中的元素。
- 其他:
Object[] toArray()
: 将 HashSet 中的元素转换为一个 Object 类型的数组,并返回该数组