Looking up values from Map/HashMap  when Objects are used as keys

I'm trying to understand why Map/HashMap don't test for equals() when looking up a key ( which is an Object that overrides equals() and hashCode()) in the Map.
I've written this code, based on some code from the SCJP book, but it is not exactly the same, this code talks about a different issue not addressed in the book.
I've added my questions inside the comments below, I think that is the best way I can ask it.
import java.util.*;
class Bird{
     public String name;
     public Bird(String name){
          this.name = name;
     //Override equals()
     public boolean equals(Object o){
          if(((Bird)o).name.equals(this.name)){
               return true;
          }else{
               return false;
        //Override hashCode
     public int hashCode(){
          return name.length();
class TestMapLookup{
     static public void main(String[] args){
          Map<Object, Object> hashMap = new HashMap<Object, Object>();
          Bird b = new Bird("crow");
          hashMap.put(b, "somevalue");
          //according to the book, the map object calls the key's (Bird object's)
          //hashCode() first and then equals()
          //to find this key in the map
          System.out.println(hashMap.get(b));
          //Using the b reference to lookup value
          //ouputs - somevalue
          System.out.println(hashMap.get(new Bird("crow")));
          //Using a new Bird object to lookup value
          //outputs - somevalue
          //because Bird overrides equals and hashCode
          //otherwise we'd get null
          //Now change the name of the bird in the b reference
          b.name = "sparrow";
          //Notice that the crow's hashCode is 4
          //sparrow's hashCode is 7 , in the above implementation of hashCode
          System.out.println(hashMap.get(b));
          //Again using b reference to lookup value
          //ouputs - null
          //because the hashCode of b.name does not match
          //the hashCode of any of the keys stored in the map
          System.out.println(hashMap.get(new Bird("crow")));
          //This also outputs null
          //for the same reason that there's no key in the map
          //with a hashcode of 7
          //This is where it becomes strange......................
          //Change the name of the bird in the b reference
          //so that the new name has the same hashCode, as the key in the map
          b.name = "dove";
          System.out.println(hashMap.get(b));
          //In the above - the hashCode matches
          //but equals() fails
          //even though equals() fails, the key is still located and the value is output
          //output is "somevalue"
          //same here:
          b.name = "1234";
          System.out.println(hashMap.get(b));
          //output is "somevalue" instead of null
          b.name = "abcd";
          System.out.println(hashMap.get(b));
          //output is "somevalue" instead of null
          //why does it output "somevalue" instead of null , even though when the map
          //looks up the key , equals() returns false?     
          System.out.println(hashMap.get(new Bird("crow")));
          //In this case ( new Bird reference ) it prints null
}I'm aware of best practices in coding and coding conventions but haven't used them here, because this is in preparation for SCJP - which tests on a lot of different things.
I appreciate any info.

It is correct that b is referring to the same object that the map's key is pointing to, but why does the following
print null , instead of "somevalue"?
at these lines in the code above.
b.name = "sparrow";
System.out.println(hashMap.get(b));Because the hashCode used when you stored b was 4, and now it's 7. You should read the Wikipedia article on Hashtable, but a simplistic explanation is that a HashMap has a bunch of "buckets," say 10, each indexed with a number 0-9. To decide which bucket to put a new key-value pair in, you take the hashcode (say 2112) and take the remainder of hashcode/number of buckets (in this case, 2112%10=2). So when you store the key-value, it gets "put" in this bucket.
When you change the hashcode of b by changing its name attribute, it doesn't change the fact that the pair is in that bucket. But, it now looks in the wrong bucket and so can't find the pair.
A hashtable gets its good efficiency by not having to look through all values to find the pair. It can jump directly to the correct bucket, which takes constant time instead of being dependent on the number of items in the collection.
endasil wrote:
You should never, ever change an object being used as a key in a map.I guess this is a best practice, I just wanted to try changing the key object to test a few things for SCJP, which does not test on coding best practices but tests on how the code behaves.Yep, and what you should take away is that this is WHY it's bad to change the key :).

Similar Messages

  • Fetch the value from a HashMap through EL

    Hi,
    I have this question,
    how can we get a value from a HashMap through EL. is there any way to do that.
    for example i have a hashmap in my bean and i want to place the value of of certain attributes on the page. specific to the key values in the hashmap.

    Just by the key.
    ${bean.map.key}roughly resolves to bean.getMap().get(key).

  • How stop PS6 from removing the DPI value from an image when using "save for the web"?

    How stop PS6 from removing the DPI-value from an image when using "save for the web"?
    Example:
    - Open a tif image, that contains a dpi value (resolution).
    - Use the splice tool in PS6.
    - Export the slices with "Save for web", as gif-files.
    Then the dpi value is removed, the gif files has no dpi value (it's empty).
    How can we stop PS6 from removing the dpi value when using "save for web"?
    OR:
    When using the slice tool, how can we save the sliced pieces without PS removing the dpi value?

    you can make your art go a little bit over the bounds. or you can make sure your artboart and art edges align to pixels

  • [svn] 4901: Only remove the children from the textFlow when they are going to be immediately replaced .

    Revision: 4901
    Author: [email protected]
    Date: 2009-02-09 09:27:39 -0800 (Mon, 09 Feb 2009)
    Log Message:
    Only remove the children from the textFlow when they are going to be immediately replaced. Side effect from SDK-18880.
    QE Notes:
    Doc Notes:
    Bugs: SDK-19177
    Reviewers: Gordon
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-18880
    http://bugs.adobe.com/jira/browse/SDK-19177
    Modified Paths:
    flex/sdk/branches/i10/frameworks/projects/flex4/src/mx/graphics/TextGraphic.as

    This is a problem of overall design.  It is not a scripting issue.
    NET USE wil only delete the drive you tell it to delete.  You will need to know in advance which drive that is.  There is no magic in WIndows.  YOu must tel it everything.
    Bill suggests GPP which is very easy to use and very flexible.  It avoids learning how to write scripts and understand much of Windows.  Just set the values and they do allof this for you.  There are checkboxes for most issues.
    Most of us have not mapped drives since shortly after the release of Vista many years ago.  Save your self a lot of headaches and use the tools that were built to do this/
    ¯\_(ツ)_/¯

  • I want to play music from my playlist when I am using slideshow of my pictures in Ipad,  but I can only choose ONE SINGLE song, and it continuously repeates itself.  Is there a way to play the complete playlist while showing my pictures?

    I want to play music from my playlist when I am using slideshow of my pictures in Ipad,  but I can only choose ONE SINGLE song, and it continuously repeates itself.  Is there a way to play the complete playlist while showing my pictures?

    You can start the playlist playing in the iPod app and then switch into the Photos app and start your (non-music) slideshow - as you've found out you can currently only select a single track in the Photos app. Whether that will change in iOS 5 I don't know, but you could try leaving feedback for Apple : http://www.apple.com/feedback/ipad.html

  • I purchased a download version of Lightroom 6 from Amazon  and when i write the license key number i'm getting this message " We are unable to validate this serial number for adobe Lightroom. Please contact Customer Support. "

    I purchased a download version of Lightroom 6 from Amazon  and when i write the license key number i'm getting this message " We are unable to validate this serial number for adobe Lightroom. Please contact Customer Support. "

    contact adobe support by clicking this link and then clicking 'still need help' as soon as it appears, https://helpx.adobe.com/contact.html

  • [svn:fx-trunk] 8551: Fix for focusSkin and errorSkin to account for bogus bitmap snapshots when objects are 3D transformed .

    Revision: 8551
    Author:   [email protected]
    Date:     2009-07-14 11:31:50 -0700 (Tue, 14 Jul 2009)
    Log Message:
    Fix for focusSkin and errorSkin to account for bogus bitmap snapshots when objects are 3D transformed.
    Bugs: SDK-17766
    Reviewer: Glenn
    QE Notes: None
    Doc Notes: None
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-17766
    Modified Paths:
        flex/sdk/trunk/frameworks/projects/spark/src/spark/skins/spark/ErrorSkin.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/skins/spark/FocusSkin.as

  • Is it possible to monitor when apps are used?  Like say I have skpe and I talk to a friend for over 3 hours, could someone look and see that I did that without having my skype or iphone?

    Is it possible to monitor when apps are used and how long they have been used for?  Like say I have skpe or oovoo and I talk to a friend for over 3 hours, could someone look and see that I did that and how long I did it for without having my skype or iphone?

    We are having an identical issue with Photos. I'm able to add information and keywords when they're in my library, but as soon as I share them, all of that information disappears. I'm hoping it's possible because it's a much nicer way to browse shared photo albums than Dropbox.

  • Acrobat X Pro 10.1.12 under Yosemite crashes when trying to use arrow keys to navigate.

    Acrobat X Pro 10.1.12 Mac
    Yosemite OS X 10.10.1
    Acrobat now crashes when attempting to use arrow keys to navigate. This is true on both MacBook Pro 15 retina and Mac Pro.

    I ended up upgrading to Acrobat XI. This works, but Adobe is up to its old tricks changing the interface from what we're used to using. They now have decided to hide all the tools. You have to delve deep into the program to find the tools, then set up your own tool menus. Lord help you finding a tool that you use too occasionally to put on a custom menu.
    Adobe has been doing this for years now. In Photoshop of olden days, it was simple to set up a brush, say, that you used frequently. Quite a few updates ago they made that vastly more difficult. And they've replaced words with happy little icons, that are not at all intuitive to use. I challenge you, too, to look at the icon for the airbrush and tell me whether it is on or off. (Sorry, this is mainly about Photoshop, but what they've done to the latest Acrobat is just as bad.)
    Of course, their ultimate cuteness in making things difficult for the user is their essential abandonment of a Help system. You can't do a simple look-up of a function -- you have to go to an internet site and sort through a bunch of forums and user comments to get any information.
    JEEZ Adobe!

  • IPhone 4 soundis very low when headphones are used

    my iPhone volume is extremely low when i plug headphones in when listening to Netflix, Pandora, etc. When i unplug the headphones, the volume is normal when coming from the speakers in the phone- this only happens when we use headphones. We took the phone to the Apple store yesterday and they completely replaced the phone with a new one- and the new one is doing the same thing- you can barely hear anything when headphones are used.. all our sounds are turned all the way up- if there a way to configure the sound settings in iTunes for your iPhone???

    This sounds silly but did you remove the plastic tabs covering each ear plug?
    If so then read here : http://support.apple.com/kb/TS2802
    Good Luck

  • Received a replacement ipod nano in early January . Works well in a sound system but keeps turning off when earphones are used. tried 3 pair but same result. When tried for support comes up as  expires. Says I have to purchase . Why????

    Received an ipod nano replacement in January. It works in a sound system but keeps turning itself of or loosing sound when earphones are used. I have tried several sets os earphones with the same result. When I just tried to seek support my Serial number comes up with warranty expired although the letter says 3 mths warranty. What gives Apple ??? Any one any advice??/

    This is usually an indication that your headphones are not plugged all the way in.  The white plastic part of the headphones should be flush with the Nano and no silver from the plug should still be visible.  The headphone jacks on the new 6G Nanos are a bit tighter than previous generations, so it requires a bit of extra push to get the headphones to pop all the way in.
    Also check make sure the jack is clear of debris such as lint.
    B-rock

  • When we are using java.io.DataInputstream and method readInt()or read doubl

    Hi
    When we are using java.io.DataInputStream some garbage value is coming
    import java.io.*;
    class DataDemo
    public static void main(String ar[]) throws IOException
    DataInputStream dis=new DataInputStream(System.in);
    double d=dis.readDouble();
    System.out.print("ERRRRR"+d);
    when we input 234.66
    its printing 7.123096485547326E-67
    If anybody know why plz answer me
    Regards
    Rani

    DataInputStream(System.in);Why do you expect this to create a double? It doesn't, see the documentation for the method, you're misusing it.

  • ItemFocusOut called twice when you are using datagrid

    Have you ever encountered itemFocusOut called twice when you
    are using datagrid. I use this event to check the text that has
    been entered.
    Also when I use regex expressions
    if((event.itemRenderer as TextInput).text.search(new
    RegExp(/.*\..*\./)) != -1){
    in the itemFocusOut method and someone enters
    234.34.234
    I get an error
    TypeError: Error #1009: Cannot access a property or method of
    a null object reference.
    at
    mx.controls::DataGrid/destroyItemEditor()[C:\autobuild\3.2.0\frameworks\projects\framewor k\src\mx\controls\DataGrid.as:4000]
    at
    mx.controls::DataGrid/itemEditorItemEditEndHandler()[C:\autobuild\3.2.0\frameworks\projec ts\framework\src\mx\controls\DataGrid.as:4897]
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at
    mx.core::UIComponent/dispatchEvent()[C:\autobuild\3.2.0\frameworks\projects\framework\src \mx\core\UIComponent.as:9298]
    at
    mx.controls::DataGrid/endEdit()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\c ontrols\DataGrid.as:4041]
    at
    mx.controls::DataGrid/mouseDownHandler()[C:\autobuild\3.2.0\frameworks\projects\framework \src\mx\controls\DataGrid.as:4296]
    Could some be so kind as shed some light on this
    situation

    I've worked around the error. I had something to do with the
    fact that the event was being twice and I worked my handling code
    around to avoid the error. However the problem with the event still
    remains. I think it is because the data it in the grid is being
    refreshed intentially after the code in the itemFocusOut is called
    that is cause the second event to fire.

  • DATAGRID FOCUS ISSUE: Focus got lost, while moving from one cell to another cell using tab key.

    Problem: Focus got lost, while moving from one cell to another cell using tab key.
    Example: In an AdvanceDataGrid, there are three columns having custom ItemRenderer with Spark TextInput control (editable=true & focusEnabled=true).
    When I try to move the focus in with in 2nd, 3rd & 4th column using tab key, focus got lost. Most of the time it’s working, but some time it doesn’t work. There’s no clue as to how may rows/columns the focus has jumped to; or whether the focus has gone out of the data grid altogether.
    Observations: I am not sure whether this problem is because of custom component implementation or it is because of some issue related to Flex Component.
    It only occurs when we perform some actions like some server call, some complex logic execution etc. at the focus out event of itemrenderer.
    There is one property of datagrid i.e. editedItemPosition which contains row & column index of datagrid. On the focus out event, it gets null when focus got lost. We tried to set it, but it didn’t work.
    Steps Performed:-
    1. Currently focus is in 2nd column i.e. Apply to #.
    2. Once I press tab key from 2nd column, it goes to 3rd column which is correct.
    3. Now if I press tab key from 2nd column i.e. Payment #, focus should go to 3rd column, but it goes out of data grid and set the focus of button which is outside data grid.

    http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2Bjtable+%2Btab+%2B%22enter+key%22&col=javaforums

  • [svn:fx-trunk] 9320: Fix Application.url property when RSLs are used.

    Revision: 9320
    Author:   [email protected]
    Date:     2009-08-14 14:49:12 -0700 (Fri, 14 Aug 2009)
    Log Message:
    Fix Application.url property when RSLs are used.
    Use LoaderUtil.normalizeURL() to normalize the Application.url property. Do the same thing for both the Halo and Spark versions of Application.
    QE notes: None.
    Doc notes: None.
    Bugs: SDK-22154
    Reviewer: Alex
    Tests run: checkintests
    Is noteworthy for integration: no
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-22154
    Modified Paths:
        flex/sdk/trunk/frameworks/projects/framework/src/mx/core/Application.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/Application.as

Maybe you are looking for

  • How to copy oracle 8.1.7 to another SID under Windows 2000

    Hi my Hope ! :) I've got problem as is written in subject. I have no idea how can I do it ? I made it under Oracle 8.0.6 but under 8.1.7 it doesn't seem works properly. Under 8.0.6 I make it more less in that way: On the source db I back up controlfi

  • Can't print to PDF file

    After my old computer crashed, I have  installed and activated Acrobat 8 Standard on a new computer. On the old machine, I had been routinely printing to PDF files.  Now, when trying to print something to a PDF file, the print progress bar stops abou

  • If RuneScape uses Java 3D why don't you need to install it?

    I was just wondering if RuneScape uses Java 3D, why doesn't anyone need to install it? Is it because the game is intirely server side and all the graphics and stuff is done over on their servers and not on your own computer? Thanks.

  • PO tax details

    hi which table contains details about excise duty, vat , cst information in oracle apps purchase order. as we need to get purchase order details with tax thanks and regards, userg

  • What do I need to remove photos from 4 G I Pad?

    What do I need to get photos from my I Pad 4G to aDVD. The Apple store told to go to places like Target. Kodak does not work with I pads. I do not have another PC to  that goes on line to go to first.