Reputation: 233
// 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 );
}
A HashMap
can't have duplicate or same key, right?
I get all entry from hashmap and put these entries into a new hashmap.
It proceed like same key.
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 );
}
}
result:
WTFcontainsKey : analyzeSrc.TextInfo@4c5 75.307 603.85535
WTFcontainsKey : analyzeSrc.TextInfo@4c5 71.74238 603.85535
WTFcontainsKey : analyzeSrc.TextInfo@4c4 66.36187 612.82837
...
Can you explain what happens here?
Why doesn't it print "processTextPosition : containsKey"?
Upvotes: 1
Views: 1316
Reputation: 299218
Probably because your Key Object doesn't override equals() and hashCode() correctly.
See the docs of Object.hashCode()
and the Section Object as a Superclass from the Java Tutorial
Or even better: Read Effective Java (2nd Ed) by Joshua Bloch
Upvotes: 4
Reputation: 14373
For using a object which you have created as a key in Map you should overwrite hashCode()
and equals()
methods. I am pretty sure that your class TextInfo
doesn't provide the implementation for the same.
Upvotes: 0
Reputation: 308269
It's hard to know without seeing the full code, but I'm reasonably sure that your TextInfo
class does not correctly implement equals()
and hashCode()
. Having those two methods implemented is a prerequisite to being useful as a key in a HashMap
.
Upvotes: 4