美文网首页
equals、hashCode、toString

equals、hashCode、toString

作者: wustzhy | 来源:发表于2020-06-01 06:23 被阅读0次

    User类 内对 equals、hashCode、toString 复写

    
    public class User {
        String name;
        int age;
        
        public User() {
            // TODO Auto-generated constructor stub
        }
        
        public User(String name, int age) {
            // TODO Auto-generated constructor stub
            super();
            this.name = name;
            this.age = age;
        }
        
        @Override
        public String toString() {
            // TODO Auto-generated method stub
            //return super.toString();
            String rString = "name:" + name + ", " + "age:" + age; 
            return rString;
        }
        
        @Override   //以后工具可自动生成
        public int hashCode() {
            // TODO Auto-generated method stub
            //return super.hashCode();
            
            int r = 17;
            r = r*31 + age;
            r = r*31 + name.hashCode();
            return r;
        }
        
        @Override
        public boolean equals(Object obj) {
            // TODO Auto-generated method stub
    //      return super.equals(obj);
            
            if (this == obj) {
                return true;
            }
            
            boolean b = obj instanceof User;
            if (b) {
                User u = (User)obj;
                if (this.name == u.name && this.age == u.age) {
                    return true;
                }
                return false;
            }else {
                return false;
            }
        }
    }
    

    equals

    public static void equals_test() {
        User u1 = new User();
        User u2 = new User();
        User u3 = new User();
        User u4 = u1;
        
        u1.name = "zhangsan";
        u1.age = 30;
        
        u2.name = "lisi";
        u2.age = 20;
        
        u3.name = "lisi";
        u3.age = 20;
        
        System.out.println(u1.equals(u2));
        System.out.println(u2.equals(u3));
        System.out.println(u1.equals(u4));
    }
    

    hashCode

    public static void hashCode_test() {
        User u = new User("zhangs", 20);
        
        HashMap<User, String> map = new HashMap<User, String>();
        map.put(u, "abc");
        
        String s = map.get(u);
        System.out.println(s); // abc
        
        String s1 = map.get(new User("zhangs", 20));
        System.out.println(s1); // null,不同对象 hash值是不同的
        //对User内部复写hashCode(), 使与成员变量相关,那么不同对象 属性值相同的 map取值也相同了
        // abc
        
    }
    

    toString

    public static void toString_test() {        
        User u = new User("zhangs", 20);
        System.out.println(u.toString()); // kkb_013_equals.User@d616cc44
        //复写toString方法后     // name:zhangs, age:20
        
    }
    

    相关文章

      网友评论

          本文标题:equals、hashCode、toString

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