• 1-22 重写equals


    package com.student;
    //重写比较规则,判断Student两学员是否是同一个对象
    //如果两学员的姓名学号相同则是同一个对象
    public class Student {
        //学员属性
        private String name;
        private int id;
        private String sex;
        
        /**
         * @param name
         * @param id
         */
        public Student(String name, int id,String sex) {
            this.name = name;
            this.id = id;
            this.sex = sex;
        }
        
        //重写equals方法
        public boolean equals(Object obj) {
            if(this == obj) {
                return true;
            }
            if(!(obj instanceof Student)) {
                return false;
            }
            Student s = (Student)obj;
            if(this.name.equals(s.name) && this.id==s.id) {
                return true;
            }else {
                return false;
            }
            
        }
        
        //重写equals方法
    //    public boolean equals(Object obj) {
    //        if(obj instanceof Student) {
    //            Student stu = (Student)obj;
    //            if(this.name.equals(stu.name)&&this.id==stu.id) {
    //                return true;
    //            }
    //        }
    //        return false;
    //    }
        
        //重写toStrint方法
        public String toString() {
            return name;
        }
    
    
        //测试方法
        public static void main(String[] args) {
            Student s1 = new Student("张三", 12,"男");
            Student s2 = new Student("张三",12,"男");
            System.out.println(s1 == s2);
            System.out.println(s1.equals(s2));
            
            System.out.println(s1);
            
            String s = "bbb";
            //打印输出s的时候默认调取了toString()方法
            System.out.println(s);
        }
    }

  • 相关阅读:
    木棍加工 [搜索]
    (转)CSP前必须记住的30句话
    [NOI2015] 程序自动分析
    JOI 2019 Final 硬币收藏
    可达性统计
    CSP-S初赛考纲内容大全
    AT2021 キャンディーとN人の子供 / Children and Candies
    AT2067 たくさんの数式 / Many Formulas
    NOIP2018提高组初赛某题
    String转Map集合
  • 原文地址:https://www.cnblogs.com/zxbaoer/p/10303291.html
Copyright © 2020-2023  润新知