package cn.itcast;
import java.util.HashSet;
import java.util.Iterator;
/*
* Set集合:
* 无序,元素不得重复
* 使用HashSet:
* 存储字符串时,不能有相同的字符串,存储数字,不能有相同的数字。
*/
public class Demo4 {
public static void main(String[] args) {
//1:创建集合对象
HashSet set = new HashSet();
//2:创建元素对象
String name = "1唐嫣";
String name2 = "2杨幂";
String name3 = "3徐静蕾";
String name4 = "4柳岩";
String name5 = "4柳岩";
//3:添加元素到集合
set.add(name);
set.add(name2);
set.add(name3);
set.add(name4);
set.add(name5);
System.out.println(set);
//4:返回迭代器
Iterator iterator = set.iterator();
//5:调用迭代器方法迭代集合
while (iterator.hasNext()) {
String thisName = (String) iterator.next();
System.out.println(thisName);
}
method();
}
//HashSet集合存储数字
public static void method(){
//1:创建集合对象
HashSet set = new HashSet();
//2:创建元素对象
int number = 1;
int number2 = 2;
int number3 = 3;
int number4 = 4;
int number5 = 5;
int number6 = 25;
int number7 = 1055;
int number8 = 0;
int number9 = 15;
int number10 = 15;
//3:添加元素到集合
set.add(number);
set.add(number2);
set.add(number3);
set.add(number4);
set.add(number5);
set.add(number6);
set.add(number7);
set.add(number8);
set.add(number9);
set.add(number10);
System.out.println(set);
//4:返回迭代器
Iterator iterator = set.iterator();
//5:调用迭代器方法迭代集合
while (iterator.hasNext()) {
int thisNumber = (int) iterator.next();
System.out.println(thisNumber);
}
}
}
|
|