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加入对象时不会调用着两个方法
    ---------------------

  • 相关阅读:
    卡牌分组
    css字体样式+文本样式
    jQuery---on注册事件的2种方式
    css3神奇的背景控制属性+使用颜色过渡实现漂亮的渐变效果
    js Dom为页面中的元素绑定键盘或鼠标事件
    ES6中Set和WeakSet
    Vue之计算属性Computed和属性监听Watch,Computed和Watch的区别
    JS数据类型和堆栈+变量比较和值的复制+参数传递和类型检测
    复习node中加载静态资源--用express+esj
    种花问题
  • 原文地址:https://www.cnblogs.com/ly570/p/11331605.html
Copyright © 2011-2022 走看看