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

Similar Messages

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

  • 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?

  • Hashmap problem

    Hi I am getting only last value from hashmap
    codes are below.
    Then I used iterator and getting
    Required string is null or empty
    jsp code
    <bean efine id="a" name="b" property="c"/>
    <bean efine id="e" name="b" property="d"/>
    <%
    java.util.HashMap params = new java.util.HashMap();
    params.put("a",a);
    params.put("b",e);
    session.setAttribute("paramsName", params);
    %>
    action classs code
    Map paramsName = new HashMap();
    paramsName=(HashMap)session.getAttribute("paramsName");
    if (paramsName!=null)
    { Iterator pIter = paramsName.keySet().iterator();
    while(pIter.hasNext()){
    a=(String)pIter.next();}

    How about the following:
    create a class with instance variables of ints to be your counters:
    public int inserts = 0;
    public int updates = 0;
    public int deletes = 0;name the class something... Tally maybe.
    Might be nice to put in methods to increment each like so:
    public void incrementInserts() {
          inserts ++;
    }and so on for the other instance variables.
    then you create one of these and increment its values appropriately, then put it in the hash.
    Code would look something like this:
    Map myMap = new HashMap();
    while ( logfileIterator.hasNext()) {
         String tableName = null;
         boolean lineIsDelete;
         boolean lineIsInsert;
         boolean lineIsUpdate;
          /* put your code here to analyze the line to find out what the table name is,
              whether it's a delete, insert or update, and set above vars accordingly */
          Tally myTally = null;
          if (myMap.containsKey(tableName)) {
                       /* code for second and subsequent times you see this table name*/
                     myTally = (Tally) myMap.get(tableName);
          } else {
                     /* code for first time you see this table name */
                     myTally = new Tally();
                     myMap.put (tableName, myTally);
          if (lineIsDelete) myTally.incrementDeletes();
          /* or if you didn't write that method you could just use [u]myTally.deletes++;[/u] */
          if (lineIsInsert) myTally.incrementInserts();
          if (lineIsUpdate) myTally.incrementUpdates();
    }

  • Storing the last modified date for files in a HashMap

    This method gets a list of all the .java files in the source subdirectory, gets the last modified date for them and stores the file name and last modified date in a HashMap.
    import java.util.HashMap;
    import java.io.FilenameFilter;
    import java.io.File;
    import java.util.ArrayList;
    public class myClass
         public static void main(String[] args)
              HashMap result = getLastModified();
         static FilenameFilter javaFilter = new FilenameFilter()
            public boolean accept(File dir, String name)
                return name.endsWith(".java");
         public HashMap getLastModified()
              HashMap lastModified = new HashMap();
              ArrayList javaFiles = new ArrayList();
              File sourceDir = new File(".\\Source");
              File currentFile;
              long lLastModified;
              //get a list of all the .java files in the source directory
              javaFiles=listFiles(javaFilter);
              //for all .java files get and store the last modified date
              for(int i=0; i<javaFiles.size(); i++)
                   currentFile=(File)javaFiles.get(i);
                   lLastModified=currentFile.lastModified();
                   lastModified.put(currentFile, lLastModified);
              return lastModified;
    }The problems I am getting are:
    >
    The method listFiles(FilenameFilter) is undefined for the type myClass
    and
    >
    The method put(Object, Object) in the type HashMap is not applicable for the arguments (File, long)
    can anyone help? What's the best way to go aobut this?

    Thanks for the replies abenstex I modified it so that javaFiles is now a File[] and made the change you suggested but I still have the second problem, here's the code so far:
    import java.util.HashMap;
    import java.io.FilenameFilter;
    import java.io.File;
    import java.util.ArrayList;
    public class myClass
         public static void main(String[] args)
              HashMap result = getLastModified();
         static FilenameFilter javaFilter = new FilenameFilter()
            public boolean accept(File dir, String name)
                return name.endsWith(".java");
         public HashMap getLastModified()
              HashMap lastModified = new HashMap();
              File[] javaFiles = {};
              File sourceDir = new File(".\\Source");
              File currentFile;
              long lLastModified;
              //get a list of all the .java files in the source directory
              javaFiles=sourceDir.listFiles(javaFilter);
              //for all .java files get and store the last modified date
              for(int i=0; i<javaFiles.length; i++)
                   currentFile=(File)javaFiles;
                   lLastModified=currentFile.lastModified();
                   lastModified.put(currentFile, lLastModified);
              return lastModified;

  • Hashmap containsKey() method does not appear to work

    Hashmap containsKey() method does not appear to work
    I have an amazingly simple custom class called CalculationKey, with my own amazingly simple custom equals() method. For some reason when I call my containsKey() method on my HashMap it does not use my defined equals method in my defined key class. Do hashmaps have their own tricky way for establishing whether two keys are equal or not?
    THIS IS MY AMAZINGLY SIMPLE CUSTOM KEY CLASS
    private class CalculationKey
    private LongIdentifier repID;
    private LongIdentifier calcID;
    public CalculationKey(LongIdentifier repID, LongIdentifier calcID)
    this.repID = repID;
    this.calcID = calcID;
    public boolean equals(Object o)
    CalculationKey key = (CalculationKey)o;
    if (key.getCalcID().equals(calcID) &&
    key.getRepID().equals(repID))
    return true;
    else
    return false;
    public LongIdentifier getCalcID()
    return calcID;
    public LongIdentifier getRepID()
    return repID;
    THIS IS MY AMAZINGLY SIMPLE CALLS TO MY HASHMAP WHICH ADDS, CHECKS, AND GETS FROM THE HASHMAP.
    private Hashmap calculationResults = new Hashmap();
    public boolean containsCalculationResult(LongIdentifier repID, LongIdentifier calcID)
    if (calculationResults.containsKey(new CalculationKey(repID, calcID)))
    return true;
    else
    return false;
    public Double getCalculationResult(LongIdentifier repID, LongIdentifier calcID)
    return (Double)calculationResults.get(new CalculationKey(repID, calcID));
    public void addCalculationResult(LongIdentifier repID, LongIdentifier calcID, Double value)
    calculationResults.put(new CalculationKey(repID, calcID), value);
    }....cheers

    You can make a trivial implementation to return a
    constant (not recommended)What do you mean by that? Hmm.. I guess you mean that
    you shouldn't use the same constant for all objects?
    But don't see the int value of an (immutable) Integer
    as constant?
    /Kaj
    You can write hashCode to just always return, say, 42. It will be correct because all objects that are equal will have equal hashcodes. Objects that are not equal will also have equal hashcodes, but that's legal--it just causes a performance hit.
    The value is that it's really really simple to implement: public int hashCode() {
        return 42;
    } So you can use it temporarily while you're concentrating on learning other stuff, or during debugging as a way to confirm that the hashCode is not the problem. (Returning a constant from hashcode(), rather than computing a value, is always legal and correct, so if something's behaving wrong, and you replace your hashCode method with the one above, and it still breaks, you know hashCode isn't the problem.)
    The downside is that you're defeating the purpose of hashing, and any non-trival sized map or set is going to have lousy performance.
    For a decent hashCode recipe, look here:
    http://developer.java.sun.com/developer/Books/effectivejava/Chapter3.pdf

  • HashMap

    Hi All,
    I am new to java.Please help me in using hashmap.
    I have records in Database like,
    DeptID, empName, tasks
    10 GR task1
    10 GR task2
    10 GBC task3
    20 ABC task4
    10 GBC task5
    20 GR task6
    10 ABC task7
    10 ABC task8
    10 GBC task9
    10 GR task10
    20 GBC task11
    20 GR task12
    20 GBC task13
    10 GR task14
    20 ABC task15
    now i am fetching the data and putting in my Java Bean.
    Now my requirement is i have to get the count for paticular deptID(For Example 10) and for partcular empName(For Example GR) how many tasks are there and appended task data.
    output is like:
    DeptId empName count appending the taks data
    10 GR 7 task1,task2,...
    10 ABC 5 task 4,task7...
    10 GBC 4
    20 GR 2
    20 GBC 5
    I am trying it to achieve using HashMap.
    HashMap s = new HashMap();
    MyBean m = new MtBean();
    s.put(m.getDeptId()+"-"+m.getEmpName() , here value is appending the taks data );
    Hash map allows duplicate keys. for 10-GR keys it will append the tasksdata. i am tryinh in this way.
    Please guide me.
    Thanks in adv..

    Map<String,List<String>> s = new HashMap<String,List<String>>();
    ... but what sabre said is better, unless you require the whole recordset be retained in memory for subsequent processing; or you can't order by for some reason.
    Cheers. Keith.

  • How to print values in a HashMap

    Hi
    I am new to Java
    I am using a HashMap where key is a String and the Value is again a HashMap..
    Firstly can I use it this way ...If not could you please suggest an alternative...
    If I can use it ...
    I am unable to print the values in the HashMap..
    Here "map" is a HasMap I am using..
    and I used
    map.put("name",secondMap);
    My code is
    public void printMap(Map map)
              Set keys = map.keySet();
              Iterator keyIter = keys.iterator();
              while (keyIter.hasNext())
                   Object key = keyIter.next();
                   Object value = map.get(key);
    // Here the value is again a HashMap
                   HashMap valuesMap=(HashMap)value;
                   System.out.println("KEY" + key.toString() );
                   if(valuesMap!=null)
                        Set set = valuesMap.keySet();
                        Iterator setit = set.iterator();
                        while (setit.hasNext())
                             Object keyinMap=setit.next();
                             Object valueinMap=valuesMap.get(key);
                             System.out.print("value is"+valueinMap);
    Can anybody help me in this regard.
    Thanks in advance

    Hmm, this looks pretty good to me. What behavior does this give you? For example, do you see "KEYname" printed? Are you sure that "map" is actually the same one you added "secondMap" to?

  • Sorting HashMap based on values

    I need to sort a hashmap based on the values, but also need to keep the keys available for retrieving the values.
    Example:
    key value
    1 c
    2 a
    3 b
    Desired Result
    2 a
    3 b
    1 c
    Thanks for your help.

    You can do this by getting all the Map.ENTRY values in a HashMap object then using a custom Comparator object to sort them by value.
    like this:
    HashMap hashMap =  // your HashMap
    Set entrySet = hashMap.entrySet;
    /* Now add them into a list and use the Collections
    * class to sort them.
    ArrayList list = new ArrayList();
    list.addAll(entrySet);
    Collections.sort(list, yourSpecialComparator);Hope this helps.

  • Vector and Hashmap with the same Content

    Hi Folks
    I have the following Problem, i want to set the same Content in a Vector as in an existing HashMap (both static!)
    These are my trials, both did not work.
    1.)
    static Hashmap hashMap = new HashMap();
    static Vector vector = new Vector(hashMap.values());
    2.)
    public static Vector getElements()
              HashMap cache = hashMap;
              Collection c = cache.values();
              Set set = cache.keySet();
              Iterator it = set.iterator();
              Vector cache1 = new Vector();
              while(it.hasNext())
                   String key = (String)it.next();
                   Element element = (Element)cache.get(key);
                   Element element2 = new Element();
    element2.setAttribut(element.getAttribut())
                   cache1.add(element2);
              cache = cache1;
              return cache;
    Does someone has advice??
    greetings
    Thomas

    Hi,
    why not simply make your method return the local vector (cache1) instead of using additional code ?
    By the way: I'm surprised because the method should return a Vector but instead returns a HashMap. Are you sure your code compiles ?
    Hope this helped,
    Regards.

  • Hashtable$Entry in HashMap

    Hi,
    I am using LRUMap from apache common collections and sometimes receives strange exception
    java.lang.ArrayStoreException: java.util.Hashtable$Entry
    at java.util.HashMap.removeEntryForKey(HashMap.java:606)
    at java.util.HashMap.remove(HashMap.java:584)
    at org.apache.commons.collections.SequencedHashMap.removeImpl(SequencedHashMap.java:469)
    at org.apache.commons.collections.SequencedHashMap.remove(SequencedHashMap.java:460)
    at org.apache.commons.collections.LRUMap.get(LRUMap.java:93)I understand what the exception means ("to indicate that an attempt has been made to store the wrong type of object into an array of objects...")
    But how it is possible that HashMap that supposed to contains objects of its internal class HashMap$Entry contains sometimes internal class of Hashtable: Hashtable$Entry ?
    Any ideas?
    Thanks!

    actually HashMap$Entry is same as HashTable$Entry except synchronizationActually there is no syncrhonization in either of them.
    so whenever writing wrong object, HashMap$Entry is containing weak refrences to HashTable$Entry.Complete and utter nonsense. There are no weak references in either of them, and neither references the other in any way.

  • I have problems with HashMap

    hello guys
    i have a problems whith this assignment.
    im usunig BlueJ
    its about a library has members and lists of the books available( a catalogue for viewing by members) and of the copies of
    these (for stock control purposes).
    information of a book (title, author, and ISBN), the title is a unique identifier.
    a book may have several copies, each with a unique stock number (an integer). a book may have no copies (if, for
    example, it has been added to the catalogue, but copies havent yet arrived.
    the library most be able to:
    - add a book to the catalogue for example when its newly published.
    - add a copy of a book to its stock when the library receives this item.
    - obtain a list of copies of a book, given its title.
    - obtain a String representation of the list of copies of a book, given its title; this should just be the title
    and list of stock numbers, for examble :( title, copies: 2000, 2001, 2002).
    now i cant make the HashMap for the stock items,
    is there anything wrong i have made or any suggestions to help me to continue my work?
    the two classes i have made so far:
    public class books
        private String title;
        private String author;
        private String ISBN;
        private int quantity;
        private int stockNumber;
        public books(String title, String author, String ISBN)
            this.title = title;
            this.author = author;
            this.ISBN = ISBN;
            //stock number satrts from 2000
            stockNumber = 1999;
        public int addquntity (int amount)
                quantity = quantity + amount;
                return quantity;
        // chang the quantity when costumer borrows a book from the library
        public int getBorowed()
            if(quantity > 0){
              quantity --;
            else{
                System.out.print("sorry the book is not avalible, try again later");
                return quantity;
        // chang the quantity when costumer rturnes a book to the library
        public void deliverBookBack()
            quantity++;
        public String toString()
            return title + " by " + author + ". ISBN = " + ISBN ;
        // change the stock number after adding any book to the library
        public int autoStockNumber()
            stockNumber ++;
            return stockNumber;
        public int getStockNumber()
            return  stockNumber;
    }======================================================
    import java.util.ArrayList;
    import java.util.HashMap;
    public class library
        private ArrayList<books> book;
        private ArrayList<members> member;
      // i coudnt make the HashMap here.
        private HashMap<books , books> stock;   
        public library ()
            book = new ArrayList<books>();
            member = new ArrayList<members>();
            stock = new HashMap<books, books>();       
        // to add a book to the catalogue, for example when its newly published (the book information)
        public void newBook(books bk)
            book.add(bk);
        public void TheStateOfTheLibrary()
            //print the library name and address
            System.out.println("BlueJ Library: 10 College Lane, AL10 9BL");
            // print list of the books (title, author, ISBN)
            System.out.println("Catalogue :");
            for (books bk : book){
                System.out.println(bk);
            System.out.println("");
             * print stock list to show all stocks in the library
             *it should show:
             *stock number, books name, by : thuthor. ISBN
            System.out.println("Stock List:");
            System.out.println("");
            System.out.println("Membership List:");       
            for (members memb : member){
                System.out.println(memb);
        public void addMember(members memb)
            member.add(memb);
        // to add a copy of a book to it's stock, when the library receives this item.
        public void addBookToStock(books sn)
           // i coudnt make it
    }thank you

    actually im new in java and i dont really understand the HashMap.A HashMap is like an array except the index values of the array aren't integers. If you declare an array like this:
    int[] nums = new int[10];
    the index values of the array are the integers 0-9. To store something in the array, you do something like this:
    nums[0] = 3;
    0 is the index value and at that index position in the array is the integer 3.
    With a HashMap, you can use index values other than integers for your array. For instance, you can use Strings:
    index value           value stored at that index position in the array
    "John"                           "232-0416"
    "Sally"                          "451-0091"To add an index value to the map and store a value at that index position, you would do this:
    myMap.put("Jane", "456-7654");
    To get the telephone number at index position "John", you would do this:
    myMap.get("John");
    However, you have to do a little more work on the object returned by get(). When you add objects, like String objects, to one of java's collections, they are automatically converted to type Object first and then added to the collection. Then, when you retrieve objects from a collection, they are returned as type Object, so you need to cast them to their original type:
    String result = (String) myMap.get("John");
    That statement gets you whatever is stored at index position "John" in the array, which happens to be the String "232-0416". You don't have to make that cast in java 1.5 when you use generics, which is what you are doing.
    One last point: in HashMap lingo, the index values in the array are called "keys".
    i have an error " cannot find symbol- method put(int,books)You defined your HashMap like this:
    private HashMap<books , books> stock;
    That tells java that you are going to be using 'books' objects for the index values of the array, and that the values stored at those index positions will be 'books' objects. But here:
    public void addBookToStock(Books sn, Books b)
            int key = sn.getStockNumber();
            stock.put(key,  b);       // the error is in this line.
    }you are trying to use an int as the index value of the array. Since you told java you would be using "books" as index values, it produces an error.
    You should also rename your Books class to "Book". A Book object does not consist of several books--it represents only one book. If you had a collection containing a bunch of Book objects, then it would make sense to name the collection "Books".

  • Iterate through HashMap and .....

    Hi friends,
    I have a HashMap with say following entries..
    (ad_key1 , value1)
    (ad_key2 , value2)
    (ad_key3 , value3)
    (ad_key4 , value4)
    (hk_key1 , value1)
    (hk_key2 , value2)
    (hk_key3 , value3)
    (hk_key4 , value4)
    Now my requirement is that i have to iterate through the hashmap and get all the values for the keys starting with ad_ , and not just that whils storing it in some other place remove that ad_ part and store the remaining. so removing the other part od_... and storing it is fine, i will do that.
    But the problem is how do i iterate through the HashMap in a way that i retreive first key then check if it is starting with ad_ , then retreive second key and check that whether it is starting with ad_ and so on .
    please do help,
    thanks in advance

    import java.util.Iterator;
    import java.util.HashMap;
         public class IteratorExample
              public static void main(String args[])
                   HashMap hashMap = new HashMap(); // Constructs a new empty HashMap
                   hashMap.put( "One", new Integer(1) ); // adding value into HashMap
                   hashMap.put( "Two", new Integer(2) );
                   hashMap.put( "Three", new Integer(3) );
                   System.out.println("Retriving all keys from the HashMap");
                   //     retrive iterator from keySet of the hashmap
                   Iterator iterator = hashMap.keySet().iterator();
                   while( iterator. hasNext() )
                        System.out.println( iterator.next() );
         }

Maybe you are looking for