Hashmap in Hashmap as Key?

Can anybofy let me know, what could be the possible disastrous outcome of keeping Hashmap in Hashmap as Key?
Could it lead to inconsistent behaviour?
If its not a good idea to use Hashmap as key in a Hashmap what other data structure we can use for the same?
Thanks,
Amit G.

Hello Amit,
I have a question - "Will the contents of the HashMap, which is the key to your second HashMap, change over a period of time.".
See sample below -
import java.util.HashMap;
import java.util.Map;
public class Foo {
     private Map<Map, String> mainMP = new HashMap<Map, String>();
     private Map<String, String> one = new HashMap<String, String>();
     public static void main(String[] args) {
          Foo f = new Foo();
     Foo() {
          mainMP.put(one, "SomeStr");
          String str = mainMP.get(one);
          System.out.println("First Time : " + str);
          one.put("hello", "where");
          str = mainMP.get(one);
          System.out.println("Second Time : " + str);
}When you run the program the result will be -
First Time : SomeStr
Second Time : null
The reason is that the hashCode for a Map object depends on its contents. So Map one will have a different hashCode when it is empty and another one when it has the String "hello". So if you add or remove any object from within a Map, the hashCode will change.
Having a HashMap as a key (which changes over time) to another HashMap is a sure recipe for disaster.
If you could tell the scenarion where you are using it, maybe I could suggest a different data structure.

Similar Messages

  • Iterate thru a HashMap() to view its keys and values

    I need to iterate over the hashmap to view its keys and values
    but the hashmap in 1.5 doesnt return itearor
    is there another way to view the key and value in the hashMap
    HashMap<String, Integer> colMap = new HashMap<String, Integer>();
    String[] array = { "Internal", "Transfer ", "Settle",  };
      List<String> colnames = Arrays.asList(array);
      for (int i = 0; i < cols; i++) {
        if (colnames.contains(headers.get(i))) {
                    colMap.put(headers.get(i), new Integer(i));
      // I need to iterate over this map to get key and values
      // The code below doesnt give me the key and values
         for (Iterator iter = colMap.iterator(); iter.hasNext();)
           Map.Entry entry = (Map.Entry)iter.next();
           String key = (String)entry.getKey();
           String value = (String)entry.getValue();
     

    Maps provide methods called keySet(), values() and entrySet(). Each of those returns a Collection (Set/Collection/Set respectively) that represents a view on the Map. You can get those and get a iterator of that objects.
    If you need both the key and the value in a loop, then you should use the entrySet method.

  • HashMap of Hashmaps

    Hello, I am trying to make basically a HashMap of HashMaps, where the method gets passed in a URL, and the method creates a HashMap with the URL being the key(because I will only add each URL once and I have a check for that), and the content would be a new HashMap so I can go into that URL and add URL's into the new HashMap(Convaluted I know..) Anyways I have run into a bit of a problem and I dont know how to fix it. Basically when I do this:
         Map<T, Map<T, Map>> graphMap;
         public DemoWebGraph() {
              graphMap= new HashMap<T, Map<T, Map>>();
         }Java wants the Map inside the parameter to have a type. How would I implement something like this or am I looking at it completely wrong?
    Thanks in advance !
    - Niallsc

    niallsc wrote:
    Java wants the Map inside the parameter to have a type.Inside what parameter? And how exactly is anything "inside" a parameter?
    How would I implement something like this or am I looking at it completely wrong?Well for one thing you're attempting to construct an instance of a class that uses Generics without defining the classes of the Type parameters T and Map (bad choice of name, Map, for a Generic type).
    Recommended reading:[http://download-llnw.oracle.com/javase/tutorial/java/generics/index.html]
    db

  • Difference between Map h = new HashMap() and HashMap h1 = new HashMap()

    Hi,
    I am new to Java.I am just confuse that what are the benifits or difference between these two approaches.
    1. Map map = new HashMap();
    2. HashMap hashMap = new HashMap();
    Please reply as soon as possible.
    Thanks
    Sachin

    Well the difference is that one declares the variable "map" as type "Map"
    The second declares the variable as type "HashMap"
    Why would you want to do this?
    Lets say at some point in the future, you decide you want the Map sorted. ie use a TreeMap instead of a HashMap.
    If you have used "HashMap" everywhere in your code, then you need to change all occurences of it to TreeMap.
    However if you just used "Map", the only dependency on "HashMap" is in this one line of code.
    Which do you think would be easier to change?

  • Add hashmap to hashmap

    Hi all,
    I have a hashmap inside hashmap - it is looking like that:
    {Header7={z=8, Header1={m=19, n=20, l=18}},
    Header2={d=4, k1=20, f=6, j1=10, e=5},
    Header1={a=1, c=3, b=2},
    Header6={d=4, f=6, e=5},
    Header3={k=20, Header4={i=3, h=2, g=1}, j=10, Header5={g1=7, h1=8, i1=9}}}
    Now I want to add to the one of the inner hash for example {Header1={d=4, f=6, e=5}}
    So, i iterate, and run recursive till I got (d,4)...
    now, what is the next step ?

    It is not that easy, because now I need to iterate in
    the original Hashmap to the correct HashMap
    (Header1...) and I don't want to loose the data from
    the toAdd HashMap.I don't get your point. Why do you lose any data, and why do you need to iterate through a Hashmap? Shouldn't you be doing a look-up?
    Maybe you might want to rethink your data model.

  • Is a HashMap of HashMaps a bad idea?

    Hi,
    I have a data file to parse through, and when storing the elements of the file, it seems convenient for me to make a HashMap that has a String for a key and a HashMap as a value. Is this a bad idea? I can mess around with ArrayLists and also succeed, but it is not as straightforward as this HashMap idea.
    Thanks.

    my data is kind of structured like this:
    every node has associated neighbors. there are properties for each neighbor. assume that each node has X neighbors. then for the inner HashMap, there would be X entries. the key would be the neighbor, and the value would be the property.
    now, assume that there are Y nodes represented in the file. then there will be Y of these inner HashMaps. so I create the outer HashMap. the key is the node's name and the value is the inner HashMap described above.
    my concern is that this may be wasteful to have all these HashMaps?

  • How to get the key value of a HashMap?

    Hi,
    I have a HashMap which obviously has key/value pairs. e.g. 1=3, 2=6 etc. I can get the value by using the method xxx.get(key), but I want to be able to get the value of the key. For example, when I have the value 3 I want to be able to get the value of the key that identifies it, in the example above it would be 1.
    Is there a way to do this.
    I'd appreciate any help.
    Thanks,
    Chris

    A HashMap guarantees unique keys, but not unique values. In the following situation:
    a=2
    b=5
    c=2
    If you wanted to do a lookup based on the value, what would your lookup of 2 return? a or c?
    At any rate, if you can guarantee that your values will be unique, you could always fill a second HashMap while filling the first; the second HashMap would simply have the original values as the keys, and the original keys as the values.

  • How to get first item of hashMap w/out knowing the key

    Hi
    can someone tell me if there is a way to get first item from a hashMap when you dont know what the key is. as the get method expects a defined 'key'
    reason I am asking this:
    I am using struts 2 UI <s:radio> tag. this tag takes a hashmap and creates radio maps. it has a 'value' attribute and if something is passed to this attribute then that radio button is checked by default. the list that contains radio buttons is created dynamically so i dont know what is actually in the hashMap key's. but i do know that key's are string.
    so just wondering if there is a way to get first item from a hashmap without knowing the key...

    thanks for the quick reply.
    posted in java forums because thought it was a java API/workaround question. gave a little history because i didnt want people to start questioning my use of HashMap for this purpose..
    anywhose..i've found a workaround.
    If someone has a similar problem:
    as the hashmap is being populated dynamically....set a String member of class to contain the first key thats being put in the hashmap. then have struts tag pick up that value.
    also, through your post and reading hashMap api...its usefull to know that hasMaps do not gurantee the order of elements in it. So now I am using a TreeMap.
    Thanks

  • Need help to map a key in hashmap

    hi guys,
    I want to find a value from hashmap.
    But the key should be matched a regex.
    I want something like...
    hashmap.contains(regex key)Thanks in advance...

    Dhaval.Yoganandi wrote:
    But I dont want to iterate through all the keys...Then stop as soon as you've found one.
    Edit: Why don't you want to iterate through all the keys?
    is there any other solution ? Otherwise I've to go for iteration..Not really. You could store your data in a different data structure that is more useful for searching for regex, but all solutions will come down to linearly searching through all (or some) elements and checking the regex.
    If you don't really need the full power of a regex, then you might find a better datastructure, for example using a Trie for prefix-matching.

  • Strings as hashmap keys

    If I use a string (a file name, for example) as the key for a hashmap put call, and then later try to retrieve the stored object using the same string, but this time hard-coded, will my object be retrieved? That is, will the dynamically loaded key and the hard-coded key be seen as the same object?
    that is ...
    image is read in from a file
    image is stored in hashmap, using filename as key
    retrieval is attempted using image title "image.gif" - is it successful?

    Do you mean this? String key = getStringSomehowSuchAsFielname();
    map.put(key, value);
    value = map.get("image.gif"); // I put with a variable but retrieve with a constant, so will it work?If that's what your'e asking, then yes, it will work. As long as the object that you use for a key properly overrides equals and hashCode, then it can be used as a key in a Map.
    "Properly overrides..." means that the state of the object is used the way you want it to be used for determining equality. In the case of java.lang.String, they're overriden the way you'd expect--i.e., using the sequence of characters in the string to determine equality.
    Make sense?

  • 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 :).

  • Vector as a HashMap key

    Hi all, I want to use Vector position as a key of hash map. Do you think that it is work? And could you mind show me some sample code. Thanks!!!

    It'll work. Here's some code that follows. However, in my sample, I'd rather store 'user' as the key to the HashMap. Also, the code below won't allow for the list to be sorted or anything after it is added to the HashMap.
    import java.util.*;
    public class VectorAndHashMap
        static class Preference
            String color;
            String fontSize;
            public Preference(String _color, String _fontSize) {
                color=_color;
                fontSize=_fontSize;
            public String toString() {
                return color+"/"+fontSize;
        public static void main(String[] args)
            Object[] users = {"smith", "brown", "jones"};
            // create the Vector
            Vector v = new Vector(Arrays.asList(users));
            Object[] prefs = { new Preference("blue", "big"),     // smith's
                               new Preference("blue", "small"),   // brown's
                               new Preference("red", "medium") }; // jones's
            // create the HashMap
            HashMap hashmap = new HashMap();
            // load the HashMap
            for(int i=0; i<v.size(); i++)
                hashmap.put(new Integer(i), prefs);
    // lookup index for "brown"
    int j=0;
    boolean found = false;
    for(j=0; j<v.size(); j++) {
    String user = (String)v.get(j);
    if(user.equals("brown")) {
    found = true;
    break;
    // retrieve record
    if(found) {
    Preference pref = (Preference)hashmap.get(new Integer(j));
    System.out.println("brown's record: " + pref);

  • Sending an XML file to a hashmap, using one of the elements as a key?

    I am looking for a way to read an XML file to a hashmap.
    So far I have learned to use javax.xml.parsers.*; tools to read the XML file
    and I can send different elements of the XML file to the screen all day.
    here is some snippets of what I'm doing now:
    public class GLDefaultLoader {
      protected String xmlFileName = "gl.xml";
      private Document loadXML(String filename) throws Exception {
        filename= "gl.xml";
        Document doc = null;
        try {
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
          DocumentBuilder db = dbf.newDocumentBuilder();
          db.setErrorHandler(new com.abcsinc.fwk.dom.MySaxErrorHandler());
           doc = db.parse(new File("gl.xml").getAbsolutePath());
        } // after this we do variuos catches
    // here Im getting started on my hashmap
    private HashMap buildGLDefaultsItems(Document doc) throws IOException,
          ParserConfigurationException,
          SAXException {
        HashMap hashMap = new HashMap();
        doc.getDocumentElement().normalize();
        System.out.println("Root element of the doc is " + doc.getDocumentElement().getNodeName());
        NodeList listOfQueries = doc.getElementsByTagName("glDefaultsItem");
        int totalQueries = listOfQueries.getLength();
        System.out.println("Total number of Queries : " + totalQueries);----------------------------------------
    I think I'm going In the right direction but I'm kinda stuck, wallowing in ignorance maybe, lol

    front

  • Returning a HashMap K, M from a method of a class typed M

    So, this is what I have. I have a class parameterized for a bean type of a collection it receives, and in a method of the class, I need (would like) to return a HashMap typed as <K, M> as in:
    public class MyClass<M> {
       private Collection<M> beanList;
       public HashMap<K, M> getMap(  /* what do I do here */ );
    }I tried to cheat from looking at the Collections.sort method, knowing it uses the List type in its return type as in:
    public static <T extends Comparable<? super T>> void sort(List<T> list)So, I am trying:
    public HashMap<K, M> getMap(Class<K> keyType)But, it is telling me I need to create class K.
    So... how does the Collections.sort method get away with it and I can't????
    I suppose I could write the method as:
    public HashMap<Object, M> getMap()but became somewhat challenged by my first guess.
    Any ideas... or just go with the HashMap with the untyped key?

    ejp wrote:
    provided K is inferable from the arguments.Or from the assignment context:
    Set<String> empty = Collections.emptySet();
    Otherwise you have to parameterise the class on <K, M>.You may also specifically provide K when you use the method if the context doesn't give the compiler enough information or if you want to override it.
    Example:
    Set<Object> singleton1 = Collections.singleton("Hello"); //error
    Set<Object> singleton2 = Collections.<Object>singleton("Hello"); //fineEdited by: endasil on 14-May-2010 4:13 PM

  • Multiple query results in HashMap

    Hi,
    Can anybody tell me how I can store multiple results of a select query in a HashMap. I basically know how to do it but here is the problem:
    I want the table ids to be the keys and ArraySets containing database data to be the values of the HashMap. But whenever I add a new key/value pair to the HashMap all the values get overridden with the ArraySet I add.
    Here is my code:
    public HashMap getResults() throws Exception {
    Class.forName(org.gjt.mm.mysql.Driver);
    Connection con = DriverManager.getConnection(jdbc:mysql:///myDbName?user=user&password=password);
    HashMap hmResults = new HashMap();
    ArrayList alValues = new ArrayList();
    PreparedStatement preparedStatement = con.prepareStatement("select id, name, email from mytable");
    ResultSet resultSet = preparedStatement.executeQuery();
    if (resultSet != null) {
    while (resultSet.next()) {
    alValues.clear();
    alValues.add(resultSet.getString("id"));
    alValues.add(resultSet.getString("name"));
    alValues.add(resultSet.getString("email"));
    // the next line adds the correct key and value but also overrides all the other values in the HashMap, why?
    hmResults.put(resultSet.getString("id"), alValues);
    return(hmResults);
    The method above returns a HashMap containing the correct keys but the values are all the same.
    What am I doing wrong?
    Thanks for helping me out!

    Because your adding to the HashMap a reference to that ArrayList, not the ArrayList itself. So basically each key in your HashMap references the one ArrayList, which you repeatedly clear and update. In the end, all your keys map to the same reference, which will contain the very last information retrieved from the ResultSet.
    Simple fix... place the ArrayList alValues = new ArrayList() line inside your loop, and each key will be mapped to a different reference.

Maybe you are looking for

  • Windows 8.1 crashing Drvr irql

    I recently upgraded to 8.1 and ever since then windows has been crashing when I play games. I have tried to update my graphics drivers from the manufacturers website and also from Intels website but everytime I download the driver I "Need", it says t

  • Problem in installation of Oracle 9i database

    In the installation the OUI is left at about 34% and the last message in the installAction.log file is : DllGroup = false Appel action fileActions2.0.1.4.0 copyGroupFromJar      selectedNodes = null      copyGroup = script      permissions = null    

  • I'm having trouble connecting my iPod to my computer

    when I plug my iPod on my computer, it says scan and check so I press scan and check then it says that my iPod was fixed but after that, i try to sync my ipod, itunes says that it failed so i tried restoring it. it is still doing the same thing so no

  • Why does the web look TERRIBLE on my new Retina display?

    The new retina display is fantastic, but browsing the web looks horrible.  Can anything be done to improve the web browsing experience? 

  • Startup Scripts error

    Hi All, Can anybody let ne know why I am getting below javascripts error when starting InDesign When I remove InDesign preferences and restsrt InDesign then these script messages goes away. Regards, Alam