Set接口和List接口一样,同样继承自Collection接口,与其接口方法基本一致,只是比Collection接口更加严格,与List接口不同的是其元素无序,并且保证元素不重复。
主要实现类:HashSet和TreeSet
1、HashSet(存储)特点:根据对象的哈希值来确定元素在集合中的存储位置,具有良好的存取和查找性能。
示例:用法
1 import java.util.*;
2 public class Example07 {
3 public static void main(String[] args) {
4 HashSet set = new HashSet(); // 创建HashSet集合
5 set.add("张三"); // 向该Set集合中添加字符串
6 set.add("李四");
7 set.add("王五");
8 set.add("李四"); // 向该Set集合中添加重复元素
9 Iterator it = set.iterator(); // 获取Iterator对象
10 while (it.hasNext()) { // 通过while循环,判断集合中是否有元素
11 Object obj = it.next();// 如果有元素,就通过迭代器的next()方法获取元素
12 System.out.println(obj);
13 }
14 }
15 }
示例:存储字符串
1 import java.util.*;
2 class Student {
3 String id;
4 String name;
5 public Student(String id,String name) { // 创建构造方法
6 this.id=id;
7 this.name = name;
8 }
9 public String toString() { // 重写toString()方法
10 return id+":"+name;
11 }
12 }
13 public class Example08 {
14 public static void main(String[] args) {
15 HashSet hs = new HashSet(); // 创建HashSet集合
16 Student stu1 = new Student("1", "张三"); // 创建Student对象
17 Student stu2 = new Student("2", "李四");
18 Student stu3 = new Student("2", "李四");
19 hs.add(stu1);
20 hs.add(stu2);
21 hs.add(stu3);
22 System.out.println(hs);
23 }
24 }
运行结果:
之所以没有去掉重复元素,是因为在定义Student类时没有重写hashCode()和equals()方法。
2、TreeSet(排序)特点:以二叉树的方式来存储元素,可实现对集合中的元素进行排序。
示例:用法
1 import java.util.TreeSet;
2 public class Example11 {
3 public static void main(String[] args) {
4 TreeSet ts = new TreeSet();
5 ts.add(3);
6 ts.add(1);
7 ts.add(1);
8 ts.add(2);
9 ts.add(3);
10 System.out.println(ts);
11 }
12 }
以上为Set接口的用法,下面文章将继续介绍Map接口。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)