zoukankan      html  css  js  c++  java
  • equals与hashcode

    java代码:

    public class A {   
        private String name;   
       
        /**  
         * @return the name  
         */   
        public String getName() {   
            return name;   
        }   
       
        /**  
         * @param name  
         *            the name to set  
         */   
        public void setName(String name) {   
            this.name = name;   
        }   
       
        /*  
         * (non-Javadoc)  
         *   
         * @see java.lang.Object#equals(java.lang.Object)  
         */   
        @Override   
        public boolean equals(Object obj) {   
            System.out.println("equals");   
            return true;   
       
        }   
       
        /*  
         * (non-Javadoc)  
         *   
         * @see java.lang.Object#hashCode()  
         */   
        @Override   
        public int hashCode() {   
            System.out.println("hashcode");   
            return 1;   
        }   
       
    }   
     

    java代码

    public void testHashA() {   
            A a = new A();   
            Set l = new HashSet(http://www.amjmh.com/v/);   
            for (int i = 0; i < 10; i++) {   
                a = new A();   
                a.setName(String.valueOf(i));   
                l.add(a);   
            }   
            System.out.println(l.size());   
            for (Iterator iter = l.iterator(); iter.hasNext();) {   
                A element = (A) iter.next();   
                System.out.println(element.getName());   
       
            }   
       
        }   
    输出为:
    hashcode
    hashcode
    equals
    hashcode
    equals
    hashcode
    equals
    hashcode
    equals
    hashcode
    equals
    hashcode
    equals
    hashcode
    equals
    hashcode
    equals
    hashcode
    equals
    1//只有一个元素
    0//第一个元素
    List、map加入对象时不会调用着两个方法
    ---------------------

  • 相关阅读:
    23、Linux实操篇——RPM与YUM
    22、Linux实操篇——进程管理(重点)
    21、Linux实操篇——网络配置
    20、Linux实操篇——磁盘分区、挂载
    19、Linux实操篇——组管理和权限管理
    18、实操篇——实用指令
    17、实操篇——用户管理
    UVALive 2521 Game Prediction 题解
    UVALive 2517 Moving Object Recognition(模拟)
    UVALive 2324 Human Gene Functions(动态规划)
  • 原文地址:https://www.cnblogs.com/ly570/p/11331605.html
Copyright © 2011-2022 走看看