文章目录
Set接口与List接口最大的不同在于 Set接口中的内容是不允许重复的。Set接口并没有对Collection接口继续宁扩充,而List接口对Collection进行了扩充。因此,在Set接口中没有get()和set()方法。
有借口就有相应的实现类,在Set接口中有常用的两个子类:HashSet(无序存储)、TreeSet(有序存储)。
1. Set接口的常用子类与使用
举例: HashSet使用
import java.util.HashSet;
import java.util.Set;
public class TestHashSet {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
// 添加元素
set.add("aaa");
set.add("hhh");
set.add("bbb");
set.add("aaa"); // 重复元素
set.add("eee");
set.add(null); // 空值
System.out.println(set);
}
}
举例:TreeSet使用
public class TestTreeSet{
public static void main(String[] args) {
Set<String> set = new TreeSet<>();
// 添加元素
set.add("aaa");
set.add("hhh");
set.add("bbb");
set.add("aaa"); // 重复元素
set.add("eee");
// set.add(null); // 不允许存放空值
System.out.println(set);
}
}
通过上述例子,我们可以发现:HashSet和TreeSet的特点和区别:
- HashSet: 不允许元素重复,无序存储(根据hash码来保存元素),允许存放null值。
- TreeSet: 不允许元素重复,按照升序排序,不允许存放null值。
2. TreeSet排序分析
我们上面观察到了TreeSet子类可以进行排序,当插入元素时,是按照升序方式进行排序的。那么我们想要对一个对象数组进行排序处理,有什么办法呢?
- 对象所在的类要实现Comparable接口并覆写compareTo()方法。
- TreeSet构造方法中传入比较器接口实现类的对象。
2.1 Comparable(内部排序接口)
Comparable接口是排序接口。
如果类实现了Comparable接口,就意味这给类支持排序。假设现在存在“实现Comparable接口类的对象的List数组”,则该数组可以通过Collections.sort(或Arrays.sort)j进行排序。
如果“实现了Comparable接口类的对象”可以用作“有序映射(TreeMap)”中的键或“有序集合(TreeSet)”中的元素,而不需要指定比较器。
2.1.1 Comparable定义
Comparable接口仅仅只包含一个函数,如下所示:
public interface Comparable<T>{
public int compareTo(T o);
}
我们可以很容易的想到compareTo是一个实现比较的方法,那么它的返回值的范围就代表着对象的大小。
compareTo方法返回一个int值,该值有三种返回值:
< 0 :表示当前对象小于比较对象
= 0 :表示当前对象等于比较对象
> 0 :表示当前对象大于比较对象
举例:创建Person类的对象按照年龄大小排序
// Person类
public class Person implements Comparable<Person>{
private String name;
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
// 覆写compareTo()方法:实现按年龄排序
@Override
public int compareTo(Person o) {
return this.getAge() - o.getAge();
}
}
// 测试
public class TestTreeSet{
public static void main(String[] args) {
Person person1 = new Person();
person1.setAge(22);
person1.setName("Jack");
Person person2 = new Person();
person2.setAge(18);
person2.setName("Tom");
Person person3 = new Person();
person3.setAge(20);
person3.setName("Mary");
// 1.第一种方式:Personl类实现可比较接口
// 如果类是自己创建的可以实现Comparable接口;
// 但是如果类不是自己写的但是需要排序,此种方法就无法实现排序功能
TreeSet<Person> treeSet = new TreeSet();
treeSet.add(person1);
treeSet.add(person2);
treeSet.add(person3);
for(Person person : treeSet){
System.out.println(person);
}
}
}
实现Comparable接口,所得结果:
我们采用了简单Java类通过实现Comparable接口来实现对象的排序,但是这个简单Java类在实现排序时,有一个缺点!如果类是字节创建的可以实现Comparable接口,但是如果类不是自己写的,我们需要实现排序,此种方法就无法实现该功能。
2.2 Comparator(外部排序接口)
Comparator是比较器接口。
我们需要控制某个类的次序,但是该类不支持排序(即没有实现Comparator接口);那么,我们就可以建立一个比较器来进行排序。这个比较器只需要实现Comparator接口即可实现排序。也就是说,我们在没有实现Comparable接口的情况下,实现一个Comparator类新建一个比较器,然后通过该比较器对类进行排序。
2.2.1 Comparator定义
Comparator接口仅仅只包含两个函数,它的定义如下:
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}
举例:
// Person类
public class Person{
private String name;
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
// TestTreeSet
public class TestTreeSet{
public static void main(String[] args) {
Person person1 = new Person();
person1.setAge(22);
person1.setName("Jack");
Person person2 = new Person();
person2.setAge(18);
person2.setName("Tom");
Person person3 = new Person();
person3.setAge(20);
person3.setName("Mary");
// 2.第二种方式:TreeSet构造方法中传入比较器接口实现类的对象
//匿名内部类
/* TreeSet<Person> treeSet = new TreeSet<>(new Comparator<Person>(){
@Override
public int compare(Person o1, Person o2) {
return (o1.getAge() - o1.getAge()) * -1;
}
});
*/
// 采用Lambda表达式
// TreeSet<Person> treeSet = new TreeSet<>((o1, o2) -> (o1.getAge() - o1.getAge()) * -1);
//采用方法引用
TreeSet<Person> treeSet = new TreeSet<>(TestTreeSet::compare);
treeSet.add(person1);
treeSet.add(person2);
treeSet.add(person3);
for(Person person : treeSet){
System.out.println(person);
}
}
public static int compare(Person o1, Person o2){
return o1.getAge() - o2.getAge();
}
}
这个方法的核心就是实现Comparator接口来创建一个外部的构造器来实现对类的排序,这个方法的实现有三种方式,匿名内部类、Lambda表达式、方法引用三种方式即可实现。
3. 重复元素判断
在使用TreeSet子类进行数据保存的时候,重复元素的判断依靠Comparable接口完成的。但是这并不是全部的Set接口判断重复元素的方式,因为如果使用的是HashSet子类,由于其跟Comparable没有任何关系,所以他判断重复元素的方式依靠的是Object类中的两个方法:
- hash码:public native int hashCode();
- 对象比较:public boolean equals(Object obj);
**equals的作用是用来判断两个对象是否相等,**在Object里面的定义是:
public boolean equals(Object obj) {
return (this == obj);
}
这说明在我们实现自己的equals方法之前,equals等价于==,而==运算符是判断两个对象是不是同一个对象,即它们的地址是否相等。而覆写equals更多的是追求两个对象在逻辑上的相等,也可以说是值相等,也可说是内容相等。
覆写equals方法的准则:
**自反性:**对于任何非空引用值x,x.equals(x)都应返回true
**对称性:**对于任何非空引用值x和y,当且仅当y.equals(x)返回true时,x.equals(y)才应该返回true。
**传递性:**对于任何非空引用值x、y和z,如果x.equals(y)返回true,并且y.equals(z)返回true,那么x.equals(z)应返回true。
**一致性:**对于任何非空引用值x和y,多次调用x.equals(y)始终返回true或始终返回false,前提时对象上equals比较所用的信息没有被修改。
**非空性:**对于任何非空引用值x,x.equals(null)都应该返回false。
hashCode用于返回对象的hash值,主要用于查找的快捷性,因为hashCode也是在Object对象中就有的,所以Java对象都有hashCode,在Hashtable和HashMap这一类的散列结构中,都是通过hashCode来查找在散列表中的位置。
在Java对象进行比较的操作有两步:
- 第一步:要通过对象的唯一编码找到一个对象的信息。
- 第二步:当编码匹配之后再调用equals()方法进行内容的比较。
范例:覆写hashCode()与equals()方法消除重复
// 实现Comparable接口
public class Person implements Comparable<Person>{
private String name;
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Person o) {
return this.getAge() - o.getAge();
}
// 1.纯手工覆写
// 覆写equals和hashCode方法时,比较内容参与的属性也要参与hashCode计算
/*
@Override
public boolean equals(Object obj) {
if(this == obj){
return true;
}
if(obj instanceof Person){
Person that = (Person)obj;
return this.getAge().equals(that.getAge()) && this.getName().equals(that.getName());
}
return false;
}
@Override
public int hashCode() {
int h = this.age.hashCode();
h = h * 31 + this.name.hashCode();
return h;
}
*/
// 2.通过IDEA工具生成
/*
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(name, person.name) &&
Objects.equals(age, person.age);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
*/
/*
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (name != null ? !name.equals(person.name) : person.name != null) return false;
return age != null ? age.equals(person.age) : person.age == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (age != null ? age.hashCode() : 0);
return result;
}
*/
}
在覆写equals和hashCode方法的时候,有三种方法可以覆写,一种肯定是我们自己去书写方法,还有两种都是通过IDEA的快捷键去生成。在覆写equals和hashCode后应注意两点:
- 如果对象equals相等,那么它们的hashCode必然相等,但如果hashCode相等,equals不一定相等。
- 对象判断必须两个方法equals()、hashCode()返回值都相同才判断为相同。
建议:
- 保存自定义对象的时候,使用List接口
- 保存系统类的信息的时候使用Set接口(避免重复)