Java集合Set集合之HashSet
HashSet中不允许有重复值,且不按顺序排列
定义一个HashSet:
Set set =new HashSet();
HashSet方法如下:
//添加元素
set.add(1);
set.add("acc");
System.out.println(set);
//移除元素
set.remove("acc");
System.out.println(set);
//判断是否有这个值
System.out.println(set.contains(1));
//清空集合
set.clear();
System.out.println(set);
//获取集合的元素个数
System.out.println(set.size());
*** 遍历HashSet集合的方法如下:
//使用迭代器遍历集合
Iterator it = set.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
//使用for each 迭代集合(推荐使用)
for (Object obj: set) { //把set的每一个值取出来赋值给obj,直到循环set的所有值
System.out.println(obj);
}
集合中存放相同类型的元素:
//如果想要让集合只能存同类型的对象,就是用泛型
Set<String> set1 = new HashSet<String>(); //指定String为集合的泛型,那这个集合就不能存放除String类型外的值了

浙公网安备 33010602011771号