- HashSet的由来
HashSet继承了Collection,是Set接口的实现类之一。
Collection_》Set——>TreeSet HashSet
2.HashSet的构造方法
调用HashSet的无参构造方法——>创建HashMap对象并给map全局变量。
HashSet set = new HashSet();
3.HashSet的常用方法
add方法:
eg. 向HashSet集合中添加元素
set.add(“Tom”);
注意:(1)add方法实质是map全局变量调用了put方法,将数据存到了key。 因为HashMap的key不能重复,所以HashSet的key也不能重复。
(2)HashSet是无序的,即不会按照保存的顺序存储数据,因而遍历时不能保证每次的结果相同。
add方法源码如下:
//foreach循环
// for (String name : set) {
// System.out.println(name);
// }
// Iterator iterator = set.iterator();//将HashSet中数据转存至iterator
// while(iterator.hasNext()) {
// System.out.println(iterator.next());
// }
// System.out.println(set.size());//获取集合容器中有多少个元素
// System.out.println(set.isEmpty());//集合为空,true
// set.clear();//清空集合容器中元素
// System.out.println(set.isEmpty());
// boolean flag = set.contains(“Tom”);//判断元素中是否包含参数指定对象
// System.out.println(flag);
// flag =set.remove(“ABC”);//删除元素,成功返回true
// System.out.println(flag);
set.add("Tom");//不允许存储重复数据
System.out.println(set.size());
}
}