✈【【零基础 快速学Java】韩顺平 零基础30天学会Java】

和 List 接口一样, Set 接口也是 Collection 的子接口,
因此,常用方法和 Collection 接口一样
同Collection的遍历方式一样,因为Set接口是Collection接口的子接口。
【举个栗子】
package com.dingjiaxiong.set_;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* ClassName: SetMethod
* date: 2022/9/5 19:04
*
* @author DingJiaxiong
*/
@SuppressWarnings({"all"})
public class SetMethod {
public static void main(String[] args) {
Set set = new HashSet();
set.add("john");
set.add("lucy");
set.add("john");
set.add("jack");
set.add("dingjiaxiong");
set.add("fengfeng");
set.add(null);
//再次添加null
set.add(null);
// for (int i = 0; i < 10; i++) {
// System.out.println("set = " + set);
// }
//遍历
//1. 迭代器
System.out.println("=====使用迭代器=====");
Iterator iterator = set.iterator();
while (iterator.hasNext()){
Object obj = iterator.next();
System.out.println("obj = " + obj);
}
set.remove(null); //删除null
//2. 增强for
System.out.println("=====增强for=====");
for (Object o : set){
System.out.println("o = " + o);
}
//set接口对象,没有索引
}
}
运行结果
