java8 中的比较器整理(==&equals&comparable&comparator)
比较器的几种区分
== 和 equals()
1.Java中的比较运算符: == 判断两个变量引用的内存对象是否是同一个
2. Java中比较运算符的另外一种实现:equals
equals 的原始实现是
public boolean equals(Object obj){
return (this==obj);
}
由此可见还是引用的 == 去比较的对象内存地址,也就是是否引用子同一个内存对象;
所以我们一般会将其按照对象的某一个属性去进行比较
特别注意在String类中重写了继承自Object的equals方法,用以判断字符串内容是否相同.而字符串是否是同一对象,需要用 ==
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
java内置比较器用于比较对象
1.继承Comparable接口,并实现compareTo()方法
2.定义一个单独的对象比较器,继承自Comparator接口,实现compare()方法
comparable
规律
compareTo(Object o)中
this - o
这段是后来研究源码发现的规律,请以标注这一段规律为主
这里的o是前一个元素,默认是按照this -o 的规则做的升序排序,即返回结果大于0,将第二个元素this,放在o的右边,小于0,将this放在o的左边(这就是升序),但是如果我们把实现换成o-this那就会变成降序
1. return 是1(大于0)的话 后边的提前 (o this)
2. return 是-1(小于0)的话 前后顺序不变 (this --- o)
3. return 是0的话 会将这个重复的 不记录
所以 当
this - o >0 或者 this > o 时 return 1 否则 -1 的话 升序 (1 2 3 4)
this - o >0 或者 this > o 时 return -1 否则 1 的话 降序 (4 3 2 1)
this - o < 0 或者 this < o 时 return 1 否则 -1 的话 降序 (4 3 2 1)
this - o <0 或者 this < o 时 return -1 否则 1 的话升序 (1 2 3 4)
整理的几种用法方式
TreeSet会将重复删除
1. TreeSet 直接使用自动排序
TreeSet set = new TreeSet<>();
set.add(new TestComparable(1,“a”));
2.List 使用 Collections.sort(list) 排序
List l = new ArrayList<>();
l.add(new TestComparable(1,“a”));
Collections.sort(l);
3.数组 使用 Arrays.sort(array); 排序
TestComparable[] array= {
new TestComparable(1,“a”),
new TestComparable(2,“b”) }
Arrays.sort(array);
代码
package main.java.comparable;
public class TestComparable implements Comparable<TestComparable> {
public TestComparable(int age, String name) {
this.age = age;
this.name = name;
}
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public