现在的位置: 首页 > 综合 > 正文

java HashMap插入重复Key值问题

2018年03月20日 ⁄ 综合 ⁄ 共 1319字 ⁄ 字号 评论关闭

http://blog.sina.com.cn/s/blog_7c81dd59010127by.html

 

今天在用到了HashMap来遍历所有非重复的Key时遇到了一个问题,在写入数据库的时候报错--主键不能重复插入。查看了好久java文档才得以解决。

    自定义一个类型

class MyType {

    private String arga;

    private String argb;

 

    public MyType(String arga, String argb) {

        this.arga = arga;

        this.argb = argb;

    }

}

 

如果代码中用到类似HashMap<MyType, String> hm = new HashMap<MyType, String>();

那么定义两个变量  MyType mta = new MyType("aaa", "bbb");

                 MyType mtb = new MyTypr("aaa", "bbb");

                 hm.put(mta, "xxx");

                 hm.put(mtb, "xxx");

猜下HashMap中有几个元素?

 

答案是有两个,原因是mta和mtb放在了不同的内存地址里面,mta和mtb传进去的是引用,那么怎么样实现HashMap没有值相同的Key呢?

方法很简单:只需要重写两个函数 public boolean equals(Object obj); 和 public int hashCode()

如下:

class MyType {

    private String arga;

    private String argb;

    public MyType(String arga, String argb) {

        this.arga = arga;

        this.argb = argb;

    }

 

    public int hashCode(){                 
     return this.arga.hashCode() * this.argb.hashCode() ; 
   
   
    public boolean equals(Object obj) {   
       if (this == obj) {               
              return true;                  
              
       if (!(obj instanceof MyType)) {  
             return false;               
         
       
       MyType p = (MyType) obj;  
      
       if (this.arga.equals(p.arga) && this.argb.equals(p.argb)) {              
           return true ;                  
       } else {           
           return false ;  

抱歉!评论已关闭.