java基础学习集合之Set 九-6
2017-02-28 18:51
323 查看
Set集合:元素是有序的,元素值唯一,不允许重复。
HashSet:底层数据结构式哈希表,是通过元素的hashcode和equals来保证元素的唯一性。
如果元素的hashcode值相同,才会判断equals是否为true;
如果元素的hashcode的值不同,不会调用equals。
对于判断元素是否存在,以及删除等操作,依赖的方法是元素的hashcode和equals方法。
TreeSet: 可以对Set集合中的元素进行自然排序。底层数据是二叉树
排序方式一: 要让自定义对象是实现 Comparable接口,强制让对象具有比较性。,排序时当主要条件相同时,一定要判断下次要条件。
然后重写compareTo()方法。
如果想要按原样顺序输出,则让compareTo()方法返回 1。
排序方式二:当元素自身不具备比较性时,或者具备的比较性不是所需要的,这时就需要让集合自身具备比较性。
在集合初始化的时候,就让集合具有比较性。
定义比较器,将比较器作为参数传递给TreeSet集合的构造函数。
set简单的demo:
HashSet 使用
原因;
查看hs.add方法:
可以看到里面为 map。put操作继续跟进
根据源码发现;
保证唯一需要满足; hash==hash 和key==key 或者 key.equals(k)...
每个对象都是new的 hash值不一样所以需要重写hashCode方法 。key==key和equals 需要重写equals方法:
怎么使用快速写equals和hashCode方法:
TreeSet 集合使用
基于
简单使用;
TreeSet存储自定义对象
会发现直接报错,采用自然排序设置
结果:并且做了去重的操作
需求:按照年龄长度排序;
这里就不写了。
TreeSet接口图解:
比较器接口 Comparator
package set;
import java.util.TreeSet;
/**
* TreeSet
*
* @author Angus
* B比较器接口 Comparator 带参构造
*
* TreeSet(Comparator<? super E> comparator)
* 构造一个新的空 TreeSet,它根据指定比较器进行排序
*/
public class TreeSetDemo2 {
public static void main(String[] args) {
TreeSet<Student> ts = new TreeSet<>(new MyComparator());
// 创建元素对象
Student s1 = new Student("哈哈1", 11);
Student s2 = new Student("哈哈22", 12);
Student s3 = new Student("哈哈333", 13);
Student s4 = new Student("哈哈4444", 14);
Student s5 = new Student("哈哈55555", 15);
Student s6 = new Student("哈哈1", 11);
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);
for (Student s : ts) {
System.out.println(s); // 默认排序 自然排序
}
}
}
比较器:
package set;
import java.util.Comparator;
public class MyComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
int num = s1.getAge() - s2.getAge();
return 1;
}
}
匿名内部类实现
TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s1.getAge() - s2.getAge();
return 1;
}
});
一般工作中采用第二种,这样就不用频繁修改代码,只需要新建一个类MyComparator就行。。。
HashSet:底层数据结构式哈希表,是通过元素的hashcode和equals来保证元素的唯一性。
如果元素的hashcode值相同,才会判断equals是否为true;
如果元素的hashcode的值不同,不会调用equals。
对于判断元素是否存在,以及删除等操作,依赖的方法是元素的hashcode和equals方法。
TreeSet: 可以对Set集合中的元素进行自然排序。底层数据是二叉树
排序方式一: 要让自定义对象是实现 Comparable接口,强制让对象具有比较性。,排序时当主要条件相同时,一定要判断下次要条件。
然后重写compareTo()方法。
如果想要按原样顺序输出,则让compareTo()方法返回 1。
排序方式二:当元素自身不具备比较性时,或者具备的比较性不是所需要的,这时就需要让集合自身具备比较性。
在集合初始化的时候,就让集合具有比较性。
定义比较器,将比较器作为参数传递给TreeSet集合的构造函数。
set简单的demo:
package set; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * * @author Angus * Collection * list 元素有序 可以重复 * set 元素无序 唯一 */ public class SetDemo { public static void main(String[] args) { Set<String> set = new HashSet<String>(); set.add("hello"); set.add("world"); set.add("java"); //遍历 无序的只能用迭代器遍历 不能用for 应为get需要有序 可以用增强for Iterator<String> it = set.iterator(); while(it.hasNext()){ String next = it.next(); System.out.println(next); } //增强for遍历 for(String s : set){ System.out.println(s); } } }
HashSet 使用
package set; import java.util.HashSet; /** * * @author Angus * HashSet 存储自定义对象 * 需求; 我们认为一个对象的如果成员变量值都相同 则为同一个对象 */ public class HashSetDemo2 { public static void main(String[] args) { // 创建对象 HashSet<Student> hs = new HashSet<Student>(); // 创建元素对象 Student s1 = new Student("哈哈1", 11); Student s2 = new Student("哈哈2", 12); Student s3 = new Student("哈哈3", 13); Student s4 = new Student("哈哈4", 14); Student s5 = new Student("哈哈5", 15); Student s6 = new Student("哈哈1", 11); hs.add(s1); hs.add(s2); hs.add(s3); hs.add(s4); hs.add(s5); hs.add(s6); // 遍历 for (Student s : hs) { System.out.println(s); //输出后发现 哈哈1 11岁的并没保证唯一 ,重写equals方法解决 } } }
原因;
查看hs.add方法:
/** * Adds the specified element to this set if it is not already present. * More formally, adds the specified element <tt>e</tt> to this set if * this set contains no element <tt>e2</tt> such that * <tt>(e==null ? e2==null : e.equals(e2))</tt>. * If this set already contains the element, the call leaves the set * unchanged and returns <tt>false</tt>. * * @param e element to be added to this set * @return <tt>true</tt> if this set did not already contain the specified * element */ public boolean add(E e) { return map.put(e, PRESENT)==null; }
可以看到里面为 map。put操作继续跟进
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }跟进putVal方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
根据源码发现;
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p;
保证唯一需要满足; hash==hash 和key==key 或者 key.equals(k)...
每个对象都是new的 hash值不一样所以需要重写hashCode方法 。key==key和equals 需要重写equals方法:
package set; /** * 标准学生类 * @author Angus * */ public class Student { private String name; private int age; public Student() { super(); } public Student(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }这样就可以保证对象的唯一了。。。。。
怎么使用快速写equals和hashCode方法:
TreeSet 集合使用
基于
TreeMap的
NavigableSet实现。使用元素的自然顺序对元素进行排序,或者根据创建 set 时提供的
Comparator进行排序,具体取决于使用的构造方法。
简单使用;
package set; import java.util.TreeSet; /** * TreeSet * @author Angus * 基于 TreeMap 的 NavigableSet 实现。使用元素的自然顺序对元素进行排序, * 或者根据创建 set 时提供的 Comparator 进行排序,具体取决于使用的构造方法。 */ public class TreeSetDemo { public static void main(String[] args) { TreeSet<String> ts = new TreeSet<>(); ts.add("hello"); ts.add("world"); ts.add("java"); ts.add("world"); ts.add("abcd"); System.out.println(ts);//输出只有一个world 保证唯一 for(String s : ts){ System.out.println(s); //默认排序 自然排序 } } }
TreeSet存储自定义对象
package set; import java.util.TreeSet; /** * TreeSet * * @author Angus */ public class TreeSetDemo { public static void main(String[] args) { TreeSet<Student> ts = new TreeSet<>(); // 创建元素对象 Student s1 = new Student("哈哈1", 11); Student s2 = new Student("哈哈2", 12); Student s3 = new Student("哈哈3", 13); Student s4 = new Student("哈哈4", 14); Student s5 = new Student("哈哈5", 15); Student s6 = new Student("哈哈1", 11); ts.add(s1); ts.add(s2); ts.add(s3); ts.add(s4); ts.add(s5); ts.add(s6); for (Student s : ts) { System.out.println(s); // 默认排序 自然排序 //Exception in thread "main" java.lang.ClassCastException: set.Student cannot be cast to java.lang.Comparable //直接输出会报错。。。为什么??? } //要是排序需要: /** * A 自然排序 让类实现 接口 * 在自然排序中,根据返回值处理 * 正数 正序排序 * 负数 倒序排序 * 0 元素不添加到集合,就是保证元素唯一的原理 ,如果有相同元素会输出是哪个元素相同 */ /** * B比较器接口 Comparator 带参构造 * */ } }
会发现直接报错,采用自然排序设置
package set; /** * 标准学生类 * @author Angus * */ public class Student implements Comparable<Student>{ private String name; private int age; public Student() { super(); } public Student(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public int compareTo(Student s) { /** * A 自然排序 让类实现 接口 * 在自然排序中,根据返回值处理 * 正数 正序排序 * 负数 倒序排序 * 0 元素不添加到集合,就是保证元素唯一的原理 */ return 1; //需求按年龄大小排序 } }现在按照年龄大小排序:
@Override public int compareTo(Student s) { /** * A 自然排序 让类实现 接口 * 在自然排序中,根据返回值处理 * 正数 正序排序 * 负数 倒序排序 * 0 元素不添加到集合,就是保证元素唯一的原理 */ //需求按年龄大小排序 int mun = this.age - s.getAge(); return mun; }
结果:并且做了去重的操作
需求:按照年龄长度排序;
@Override public int compareTo(Student s) { /** * A 自然排序 让类实现 接口 * 在自然排序中,根据返回值处理 * 正数 正序排序 * 负数 倒序排序 * 0 元素不添加到集合,就是保证元素唯一的原理 */ //需求姓名长度 长度一样的清除 int length = this.name.length()-s.getName().length(); return length; }但是这样也有缺陷,有名字一样的,但是年龄不一样,所以需要多次比较。。。。。
这里就不写了。
TreeSet接口图解:
比较器接口 Comparator
package set;
import java.util.TreeSet;
/**
* TreeSet
*
* @author Angus
* B比较器接口 Comparator 带参构造
*
* TreeSet(Comparator<? super E> comparator)
* 构造一个新的空 TreeSet,它根据指定比较器进行排序
*/
public class TreeSetDemo2 {
public static void main(String[] args) {
TreeSet<Student> ts = new TreeSet<>(new MyComparator());
// 创建元素对象
Student s1 = new Student("哈哈1", 11);
Student s2 = new Student("哈哈22", 12);
Student s3 = new Student("哈哈333", 13);
Student s4 = new Student("哈哈4444", 14);
Student s5 = new Student("哈哈55555", 15);
Student s6 = new Student("哈哈1", 11);
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);
for (Student s : ts) {
System.out.println(s); // 默认排序 自然排序
}
}
}
比较器:
package set;
import java.util.Comparator;
public class MyComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
int num = s1.getAge() - s2.getAge();
return 1;
}
}
匿名内部类实现
TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s1.getAge() - s2.getAge();
return 1;
}
});
一般工作中采用第二种,这样就不用频繁修改代码,只需要新建一个类MyComparator就行。。。
最后附上JDK使用文档API 下载
相关文章推荐
- Java基础第十六天学习日记_Map集合
- java 从零开始,学习笔记之基础入门<集合>(十六)
- JAVA基础学习之final关键字、遍历集合、日期类对象的使用、Math类对象的使用、Runtime类对象的使用、时间对象Date(两个日期相减)(5)
- java基础学习集合学习笔记
- 黑马程序员 JAVA基础学习笔记 集合等
- java 基础学习-06 集合的使用 一
- 黑马程序员-java基础-集合学习笔记
- Java集合源码学习(5)_List接口的基础实现AbstractList
- 黑马程序员------Java基础学习------集合框架
- java基础学习笔记_集合
- 黑马程序员--集合框架知识总结和泛型--java学习日记7(基础知识)
- 黑马程序员学习log第五篇基础知识:JAVA的面向对象之集合总结
- java基础学习--Collection集合
- java基础学习6--集合
- java 从零开始,学习笔记之基础入门<集合>(十六)
- JAVA基础学习之 Map集合、集合框架工具类Collections,Arrays、可变参数、List和Set集合框架什么时候使用等(4)
- 黑马程序员——java基础学习(集合)
- 黑马程序员_java基础学习笔记06_集合框架
- java基础学习之集合概念总结
- 黑马程序员—java基础学习--Map集合、Collections,Arrays工具类