1.Object类
(1)toString()方法
a.如果没有重写Object类的toString()方法,则默认返回地址值
b.如果重写了(例如String类),则返回内容
(2)equals()方法
手写class的equals()方法:比较内容
@Override
public boolean equals(Object o){
if(this == o) return true;
if(o==null) return false;
//o必须是Person类
if(!(o instanceof Person)) return false;
Person p = (Person) o;
return p.name.equals(this.name)&&p.age == this.age;
}
注:String类的equals()方法也被重写过
(3)clone()方法
1.作用:复制一个属性值一样的新对象
2.使用:
需要被克隆的对象实现Cloneable
重写clone方法
使用:
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
2.Comparable接口(提供CompareTo方法)
//用于比较Student类和其他类
@Override
public int compareTo(Object o) {
Student s = (Student) o;
return this.score-s.score;
}
使用冒泡排序对类对象进行排序:
public class Compare_test {
public static void main(String []args){
ArrayList<Student>students = new ArrayList<>();
students.add(new Student("yzq",100));
students.add(new Student("yxc",22));
students.add(new Student("dwj",99));
//冒泡排序--类对象版
for(int i=0;i<students.size()-1;i++){
for(int j=0;j<students.size()-1-i;j++){
if(students.get(i).compareTo(students.get(i+1))>0){
Student t = students.get(i);
students.set(i,students.get(i+1));
students.set(i+1,t);
}
}
}
//使用Collections类的sort进行集合排序
// Collections.sort(students,(x, y)->{
// return x.getScore()-y.getScore();
// });
System.out.println(students.toString());
}
}
3.Comparator接口(提供Compare方法)
@Override
public int compare(Object o1, Object o2) {
Student s1 = (Student)o1;
Student s2 = (Student)o2;
return s1.score -s2.score;
}
}
使用compare方法前,要定义一个类对象
package bilibili.chapter12;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
public class Compare_test {
public static void main(String []args){
ArrayList<Student>students = new ArrayList<>();
students.add(new Student("yzq",100));
students.add(new Student("yxc",22));
students.add(new Student("dwj",99));
Student student = new Student();
//冒泡排序--类对象版
for(int i=0;i<students.size()-1;i++){
for(int j=0;j<students.size()-1-i;j++){
//if(students.get(i).compareTo(students.get(i+1))>0){
if(student.compare(students.get(i),students.get(i+1))>0){
Student t = students.get(i);
students.set(i,students.get(i+1));
students.set(i+1,t);
}
}
}
//使用Collections类的sort进行集合排序
// Collections.sort(students,(x, y)->{
// return x.getScore()-y.getScore();
// });
System.out.println(students.toString());
}
}