Set接口的特点
Set接口特点:
- 无序,无下标,不可重复
- 方法全部继承Collection里的方法
增加元素
//不能直接new 只能new set接口下的实现类
Set set=new HashSet();
//增加元素
set.add("小米");
set.add("苹果");
set.add("华为");
set.add("三星");
System.out.println("集合中的元素个数为:"+set.size());
System.out.println(set.toString());
删除元素
//删除元素
set.remove("小米");
set.clear();
System.out.println("集合中的元素个数为:"+set.size());
System.out.println(set.toString());
遍历元素
//遍历集合元素
//增强for循环 (没有下标,所以不能用普通for循环)
System.out.println("-------增强for循环------");
for (Object o : set) {
System.out.println(o);
}
//迭代器
System.out.println("---------迭代器--------");
Iterator it=set.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
判断
//判断
System.out.println("---------------------");
System.out.println(set.contains("小米"));
System.out.println(set.isEmpty());