java Set ,HashSet

API中比较 set 和 collection  集合都有一样的方法

* A:Set集合概述及特点   :一个不包含重复元素的 collection
* 通过API查看即可
* B:案例演示
* HashSet存储字符串并遍历
*
HashSet<String> hs = new HashSet<>();
boolean b1 = hs.add("a");
boolean b2 = hs.add("a"); //当存储不成功的时候,返回false

System.out.println(b1);
System.out.println(b2);
for(String s : hs) {
System.out.println(s);
}

 

 

HashSet存储自定义对象保证元素唯一性
* A:案例演示
* 存储自定义对象,并保证元素唯一性。

HashSet<Person> hs = new HashSet<>();
hs.add(new Person("张三", 23));
hs.add(new Person("张三", 23));
hs.add(new Person("李四", 23));
hs.add(new Person("李四", 23));
hs.add(new Person("王五", 23));
hs.add(new Person("赵六", 23));
* 重写hashCode()和equals()方法

 

 

public static void demo1() {
HashSet<String> hs = new HashSet<>(); //创建HashSet对象
boolean b1 = hs.add("a");
boolean b2 = hs.add("a"); //当向set集合中存储重复元素的时候返回为false
hs.add("b");
hs.add("c");
hs.add("d");
System.out.println(hs); //HashSet的继承体系中有重写toString方法
System.out.println(b1);
System.out.println(b2);

for (String string : hs) { //只要能用迭代器迭代的,就可以使用增强for循环遍历
System.out.println(string);
}
}

posted @ 2017-03-07 22:53  yimian  阅读(154)  评论(0编辑  收藏  举报
访问人数:AmazingCounters.com