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类型外的值了
 
 


 
 
posted @   SmallPepsi  阅读(163)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示