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

  • 相关阅读:
    python匿名函数lambda用法
    python递归函数
    python中的全局变量与局部变量
    元组,字典,集合
    WKWebView 与 UIWebView
    JSON数组字典解析
    iOS使用Instruments的工具
    CocoaPods Mac App的安装和使用
    Mac环境下svn的使用(转)
    数据存储-- Core Data的使用(二)
  • 原文地址:https://www.cnblogs.com/ly570/p/11331605.html
Copyright © 2011-2022 走看看