美文网首页
Java-API-Comparable

Java-API-Comparable

作者: 码农随想录 | 来源:发表于2018-07-18 18:35 被阅读1次
    public class Person implements Comparable {
    
        private String name;
        private int age;
        
        public Person() {
            super();
        }
        public Person(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;
        }
        
        /**
         * 建立了Person对象判断是否相同的依据。只要是同姓名同年龄就是同一个人
         * @param obj
         * @return
         */
        @Override
        public boolean equals(Object obj) {
            if(this == obj)
                return true;
            
            if(!(obj instanceof Person)){
                throw new ClassCastException("类型错误");
            }
            Person p = (Person)obj;
            
            return this.name.equals(p.name) && this.age == p.age;
        }
        /**
         * 比较年龄大小的方法。
         */
        
        
        @Override
        public String toString() {
            return "Person [name=" + name + ", age=" + age + "]";
        }
        @Override
        public int compareTo(Object o) {
            
            if(!(o instanceof Person)){
                throw new ClassCastException("类型错误");
            }
            
            Person p = (Person)o;
            /*
            if(this.age > p.age)
                return 1;
            if(this.age < p.age)
                return -1;
            return 0;*/
            return this.age - p.age;
            
        }
    }
    
    public class PersonDemo {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            
            Person p1 = new Person("lisi", 20);
            Person p2 = new Person("wangcai", 23);
            
            System.out.println(p1.compareTo(p2));
        }
    }
    

    相关文章

      网友评论

          本文标题:Java-API-Comparable

          本文链接:https://www.haomeiwen.com/subject/wudapftx.html