Set接口
不包含重复元素,最多只能包含一个null元素,不可重复
import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class SetDemo { public static void main(String[] args) { // 演示Set无序和不可重复性 Set<String> set = new HashSet<String>(); String s1="Hello"; String s2=s1; String s3="world"; String s4="你好"; set.add(s1); set.add(s2); set.add(s3); set.add(s4); Iterator<String> iterator = set.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); //print : world hello 你好 } } }
HashSet是Set接口的直接子类
import java.util.HashSet; import java.util.Iterator; public class HashSetDemo { public static void main(String[] args) { // 实例化HashSet对象 HashSet<Student> hashSet = new HashSet<Student>(); Student stu0 = new Student("100000","a"); Student stu1 = new Student("100001","b"); Student stu2 = new Student("100002","c"); //将三个元素添加到HashSet hashSet.add(stu0); hashSet.add(stu1); hashSet.add(stu2); traverse(hashSet); } //遍历 public static void traverse(HashSet<Student> hashSet) { Iterator<Student> iterator = hashSet.iterator(); while(iterator.hasNext()) { Student student = iterator.next(); System.out.println(student.no+" "+student.name+" "); } } }
HashSet特征
元素不可重复,需要重写hashCode(),equals() 方法
元素的顺序随时可变
最多只允许一个null元素