[英]Why does this hashmap have the same key twice?
// 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
不能有重復或相同的密鑰,對嗎?
我從哈希圖中獲取所有條目,並將這些條目放入新的哈希圖中。
它像相同的鍵一樣進行。
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()。
請參閱Java教程中的Object.hashCode()
文檔和Section 對象作為超類 。
在沒有完整代碼的情況下很難知道,但是我可以合理地確定您的TextInfo
類沒有正確實現equals()
和hashCode()
。 實現這兩種方法是在HashMap
用作鍵的先決條件。
要使用在Map中創建為鍵的對象,應覆蓋hashCode()
和equals()
方法。 我很確定您的TextInfo
類不會提供相同的實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.