java String类3 Comparable

//上一章说到:String类 之所以具备比较的功能就是因为他实现了Comparable 这个接口

package String;
class CDemo implements Comparable{
    private int age;
    private String name;

    public CDemo(String name,int age) {
        this.name= name;
        this.age=age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {//判断是否同名同姓
        if(!(obj instanceof CDemo)){
            throw new ClassCastException("类型错误");
        }
        CDemo p = (CDemo)obj;
        return this.name.equals(p.name)&&this.age==p.age;
    }

    @Override
    public String toString() {
        return "name = "+name+" age = "+age;
    }

    @Override
    public int compareTo(Object o) {
        if(!(o instanceof CDemo)){
            throw new ClassCastException("类型错误");
        }
        CDemo c = (CDemo)o;
        if(this.age==c.age)
            return 0;
        return this.age-c.age;
    }
}
public class ComparableDemo {
    public static void main(String[] args){
        CDemo demo1= new CDemo("LIzhuzhu",20);
        CDemo demo2= new CDemo("zhuzhu",25);
        System.out.println(demo1.compareTo(demo2));
        System.out.println(demo2.equals(demo1));
        System.out.println(demo1.toString());
    }
}

结合快捷键使用

猜你喜欢

转载自blog.csdn.net/Stitch__/article/details/82053515