hanxianlong 2009-01-14 12:53
浏览 181
已采纳

我无法解释的问题,请您一并来解释

情景上这样的:我有一个重写了equals方法的类,该类源码如下。然后用一程序将此类多次循环put到HashMap中去,但每次put到1500次左右时,就会出现NullPointerException。

  在map.put的方法中,会先去判断put进去的对象是否已经存在于map中,判断方法调用的就是该对象的重写的equals方法,如果说我写的equals有问题的话,为什么前1000多次左右不会出现问题而在最后出现问题呢?起初以为是放到HashMap中的对象太大会出现内存溢出,但并未出现outofmemory异常,用JProfiler进行监测时也发现和heap的使用也没关系……有哪位兄弟帮我解释一下……



  重写了equals方法的类:

public class myPolSchema {

    // @Field

    private String GrpContNo;

    private String GrpPolNo;



    public String getGrpContNo() {

        return GrpContNo;

    }



    public void setGrpContNo(String aGrpContNo) {

        GrpContNo = aGrpContNo;

    }



    public String getGrpPolNo() {

        return GrpPolNo;

    }



    public void setGrpPolNo(String aGrpPolNo) {

        GrpPolNo = aGrpPolNo;

    }



    public boolean equals(Object otherObject) {

        if (this == otherObject)

            return true;

        if (otherObject == null)

            return false;

        if (getClass() != otherObject.getClass())

            return false;

        myPolSchema other = (myPolSchema) otherObject;

        return GrpContNo.equals(other.getGrpContNo())

                && GrpPolNo.equals(other.getGrpPolNo());

    }

}

测试类:



import java.util.* ;

public class MultiThreading{

// implements Runnable

    Map m=Collections.synchronizedMap(new HashMap());

    //HashMap m=new HashMap();

    Hashtable t=new Hashtable();

    public myPolSchema polschema;

    public void run()

    {

        polschema=new myPolSchema();

        m.put(polschema, "UPDATE");

        System.out.println("put end at " + new Date());

    }

    public static void main(String[] args) throws Exception {

        MultiThreading t=new MultiThreading();

        for(int i=0;i <=25000;i++){

            try{

                t.run();

                //Thread.sleep(100);

            }

            catch(Exception ex){

                //在我本地测试时当运行大概1500左右次的时间就会抛出NullPointerException

                System.out.println("i is: " + i);

                throw ex;

            }

        }

    }



}



如果您从源码上看不出来我所说的问题,在此处下载源码……



  • 写回答

5条回答 默认 最新

  • Candyut 2009-01-14 13:00
    关注

    重写equals的同时需要重写hashCode方法

    可以参考:
    http://zhangjunhd.blog.51cto.com/113473/71571

    建议看《Effective Java》其中关于重写equals和hashCode的内容。

    希望以上回复对你有帮助。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料