简体   繁体   中英

comparisons using a hashMap not giving expected result

The problem at hand is that when i try to pull the value from the hashmap it is returning null.

I have a hashMap instance :

Map<Marker,Tag> theHashMap = new HashMap<Marker,Tag>();

where tag is a class that holds some simple information about the marker and the marker is a Google map marker .

I add to theHashMap at the start of the activity that this all happens in

theHashMap.put(mapController.AddMarker(new Tag(1, "City Of Dundee", DUNDEE_LOCATION, "untagged",), new Tag(1, "City Of Dundee", DUNDEE_LOCATION, "untagged",));

where mapController is a class that deals with everything googleMap related.

And mapController . AddMarker returns the marker that was added to the map.

after the hashMap is filled it is passed to the onMarkerClickListener for later reference.

I call hashMap.get(marker); from within a marker listener where marker is the marker that was clicked.

It always returns null, I thought it may be because the hashMap inside the onMarkerClick listener was a separate instance but I tried making a pointer to the original and it didn't work, i also tried hashMap.get(marker.getTitle()); and with the marker.getID() thinking that it would compare there titles but it ended with the same result.

I'll add more information if requested but for now, is there any other way of taking the value from the hashMap based on the marker that was clicked?

In your code hashMap.put(marker,key); here in this hashMap you have used key -> custom obje ct(mapper).

Hence it returns null when you called by the key. where provide key (mapper) object should match with put (mapper) key.

You have to override equals and hashcode methods in Mapper class to solve this.

EDIT:

In HashMap your key is mapper object(custom object) . As custom object(Mapper object) is key in HashMap we have to override equals and hashcode in Mapper class to fetch exact value.

If key as Primitives(int) or String Object, no need to do the above thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM