HashSet的代码示例
时间: 2023-06-05 22:04:28 浏览: 135
Java HashSet集合存储遍历学生对象代码实例
5星 · 资源好评率100%
可以参考以下代码示例:
```
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
// add elements to set
set.add("apple");
set.add("banana");
set.add("orange");
// check if an element is in the set
boolean containsApple = set.contains("apple");
System.out.println("Contains apple? " + containsApple);
// remove an element from the set
set.remove("banana");
// iterate over the set
System.out.println("Elements in set:");
for (String element : set) {
System.out.println(element);
}
// get the size of the set
int size = set.size();
System.out.println("Size of set: " + size);
}
}
```
阅读全文