四、set集合
无序、无下标、元素不可重复
1、hashSet【重点】
== 数组+链表+红黑树==
基于hashcode计算元素存储位置
当哈希吗一样的时候,调用equals,如果为true,拒接存入
package com.zheng.demo3; import java.util.HashSet; import java.util.Iterator; public class MySet { public static void main(String[] args) { //创建集合框架 HashSet<String> set = new HashSet<>(); //添加数据 set.add("1-小红"); set.add("2-小明"); set.add("3-小白"); set.add("4-小黑"); set.add("5-小红"); set.add("1-小红"); //迭代器迭代集合元素 遍历 Iterator<String> iterator = set.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
实体类
package com.zheng.demo3; public class School { private int id; private String name; public School() { } public School(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "School{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
package com.zheng.demo3; import java.util.HashSet; import java.util.Iterator; public class TestSet { public static void main(String[] args) { //1、创建集合容器 HashSet<School> schools = new HashSet<>(); //创建对象 School school1 = new School(1, "清华大学"); School school2 = new School(2, "北京大学"); School school3 = new School(3, "浙江大学"); //3、放入集合 schools.add(school1); schools.add(school2); schools.add(school3); schools.add(new School(2,"北京大学")); //4、遍历 Iterator<School> iterator = schools.iterator(); while (iterator.hasNext()){ School school=iterator.next(); System.out.println(school); } } }
2、TreeSet
存储结构:红黑树
要实现comparable接口,重写里边的方法,返回0代表元素重复
元素不重复
元素自动排序
package com.zheng.demo3; import java.util.Iterator; import java.util.TreeSet; public class MyTree { public static void main(String[] args) { //1、创建一个集合 TreeSet treeSet = new TreeSet(); //2、加入元素 treeSet.add(1); treeSet.add(3); treeSet.add(2); treeSet.add(4); treeSet.add(3); //3、迭代遍历 Iterator iterator = treeSet.iterator(); while (iterator.hasNext()) { int i = (int) iterator.next(); System.out.println(i); } } }
TreeSet案例:排列字符串的顺序
package com.zheng.demo3; import java.util.Comparator; import java.util.Iterator; import java.util.TreeSet; public class MyTreeSet { public static void main(String[] args) { //匿名内部类 TreeSet<String> set = new TreeSet<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { int n1 = o1.length() - o2.length(); int n2 = o1.compareTo(o2); return n1 == 0 ? n2 : n1; } }); set.add("he"); set.add("hhhhh"); set.add("jdjdjkdkk"); set.add("djdj"); Iterator<String> iterator = set.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
comparator:定制比较器