使用 Set 集合,存储数据。
请定义一个 Set 集合,并执行以下步骤:
public class Demo {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)\n");
HashSet<String> set = new HashSet<>();
Collections.addAll(set,"刘备","关羽","张飞","刘备","张飞");
System.out.println("集合容量是:" + set.size());
// 迭代器遍历集合
System.out.print("迭代器遍历集合: ");
Iterator it = set.iterator();
while(it.hasNext()){
System.out.print(it.next() + " ");
}
System.out.println();
// 增强 for 遍历集合
System.out.print("增强 for 遍历集合: ");
for(String s : set){
System.out.print(s + " ");
}
}
}
运行结果如下图:
以上案例存储数据到 Set 集合中,由此看出 Set 集合元素不可重复且无序。