java - 为什么这个 hashmap 有两次相同的键?

标签 java hashmap key duplicates

// same X, Y value text.
    TextInfo currXY = new TextInfo( text );

    ArrayList<TextPosition> currTextArray = textComposition.get( currXY );
    if( currTextArray != null ){
        currTextArray.add( text ); 
    } else {
        ArrayList<TextPosition> newTextArray = new ArrayList<TextPosition>();
        newTextArray.add( text );
        if( textComposition.containsKey( currXY )){
            System.out.println( "processTextPosition : containsKEy ");
        }
        textComposition.put( currXY , newTextArray );
    }   

HashMap 不能有重复或相同的键,对吧?

我从 hashmap 中获取所有条目并将这些条目放入一个新的 hashmap 中。

它像同一个键一样进行。

lineSortingMap = new HashMap< TextInfo, ArrayList<TextPosition> > ();     
    for ( Map.Entry< TextInfo, ArrayList<TextPosition> > entry : textComposition.entrySet() ) {
        TextInfo key = (TextInfo)entry.getKey();
        ArrayList<TextPosition> arrayTextPositions = entry.getValue();
        if( lineSortingMap.containsKey( key ) ){
            System.out.println("WTFcontainsKey : " + " " + key + " " + key.getX() + " " + key.getY() );
        }
        else{
            lineSortingMap.put( key , arrayTextPositions );
        }
    }

结果:

WTFcontainsKey :  analyzeSrc.TextInfo@4c5 75.307 603.85535

WTFcontainsKey :  analyzeSrc.TextInfo@4c5 71.74238 603.85535

WTFcontainsKey :  analyzeSrc.TextInfo@4c4 66.36187 612.82837

...

你能解释一下这里发生了什么吗?

为什么不打印“processTextPosition : containsKey”?

最佳答案

可能是因为您的关键对象没有正确覆盖 equals() 和 hashCode()。

请参阅 Object.hashCode() 的文档和第Object as a Superclass节来自 Java Tutorial

或者更好:阅读 Effective Java (2nd Ed) by Joshua Bloch

关于java - 为什么这个 hashmap 有两次相同的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12365169/

相关文章:

java - 我认为我可能误解了 Map 类方法

java - 由 Map.ofEntries() 创建的 map 的访问时间复杂度是否与 o(1) 的 HashMap 相同?

MySQL添加外键

java - 调用init方法失败;嵌套异常是 org.hibernate.AnnotationException : No identifier specified for entity

java - Firestore set() 方法不会将文档插入集合中,除非调用 ApiFuture<WriteResult> 的 get() 方法

java - Struts 2 中的值未从 jsp 绑定(bind)到操作类

algorithm - 经典 Cracking the Coding 面试题的运行时间 a^3 + b^3 = c^3 + d^3?

google-app-engine - AppEngine 数据存储区 key 名称中允许使用的字符

oracle - “SET FOREIGN_KEY_CHECKS = 0;”相当于Oracle

java - 从文件 BufferedReader 获取文本,输出看起来不错,但不等于 "true"或 "false"(文件中的内容)