Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Java hashMap issue

Options
  • 30-10-2014 4:44am
    #1
    Registered Users Posts: 3,793 ✭✭✭


    Hi,

    Iv been trying to populate a hashMap and it doesnt seem to work correctly even though in my head it should. Im obviously not understanding hashMap's properly so if someone can explain why this happens it would be great.

    
    
    Map <String, String> packageList;
    
    
    
    public void popMap()
        {  
                  
            for(String cl:classList)
            {
                          
                packageList.put(cl , "A");
                packageList.put(cl , "B");
                packageList.put(cl, "C");
                packageList.put(cl , "D");
            }
            
        }
    
    

    If i was to print that hashMap it displays
    LetterA=D
    LetterB=D
    LetterC=D
    LetterD=D

    Where as i need it to print
    LetterA=A
    LetterB=B
    LetterC=C
    LetterD=D


    classList is the name of the Set im populating the Map from and it works. Iterating through the Set with the for loop works and the different values are stored in the Map in the order i would expect. When i print(packageList) it gives me A B C D which is what im looking for.

    However the assigned value always outputs D.


Comments

  • Registered Users Posts: 339 ✭✭duffman85


    You have 4 calls to put in each iteration. you're overwriting the value with each call so the last call
    packageList.put(cl , "D");
    
    is overwriting what was done in
    packageList.put(cl , "C");
    
    and the previous 2 calls.


  • Registered Users Posts: 3,793 ✭✭✭Hijpo


    duffman85 wrote: »
    You have 4 calls to put in each iteration. you're overwriting the value with each call so the last call
    packageList.put(cl , "D");
    
    is overwriting what was done in
    packageList.put(cl , "C");
    
    and the previous 2 calls.
    But I thought .put creates a new key/value pair if there are no duplicates?


  • Registered Users Posts: 7,157 ✭✭✭srsly78


    It's not creating any new pairs, because you are pushing in the same values each time.

    Look at your for loop and fix it. Problem is not with the hash map, it's with what you are feeding into it.

    String cl is not changing, you need to iterate over the values of that list.


  • Registered Users Posts: 586 ✭✭✭Aswerty


    Much in line with what others have said.

    The loop is doing the following:

    Iteration 1:
    LetterA = A
    LetterA = B
    LetterA = C
    LetterA = D

    Iteration 2:
    LetterB = A
    LetterB = B
    LetterB = C
    LetterB = D

    and so on for each Letter...

    So the last assignment of each iteration is always D. That is why you are getting the result you are getting.

    Try doing only one assignment per iteration. Then find how to increase the value "A" to "B" to "C" and so on in each iteration before assigning it as the value for the key.


  • Registered Users Posts: 3,793 ✭✭✭Hijpo


    srsly78 wrote: »
    It's not creating any new pairs, because you are pushing in the same values each time.

    Look at your for loop and fix it. Problem is not with the hash map, it's with what you are feeding into it.

    String cl is not changing, you need to iterate over the values of that list.

    Sorry if I'm going on a bit much but why would cl show to be changing when a print the hash map? Am I using the wrong way to check its contents?


  • Advertisement
  • Registered Users Posts: 7,157 ✭✭✭srsly78


    Remove the for loop and write out your assignments the long way, then you can see exactly what is happening. Also try using breakpoints, so you can inspect exactly what gets put into the map each time.


  • Registered Users Posts: 403 ✭✭counterpointaud


    Hijpo wrote: »
    But I thought .put creates a new key/value pair if there are no duplicates?

    If the key is the same it's considered a duplicate, and put() will overwrite the previous entry


  • Registered Users Posts: 3,793 ✭✭✭Hijpo


    If the key is the same it's considered a duplicate, and put() will overwrite the previous entry

    I'm using each iteration of the classList set to assign a value to the hash map.
    Following srsly78 advice I used breakpoints to inspect what strings are being inserted and the keys are all correct.

    Just need to figure out how to construct the pairings now.

    If i populate the value of the hashMap before the loop
    packageList.put(null , "A");
    packageList.put(null , "B");
    packageList.put(null , "C");
    packageList.put(null , "D");
    

    Is it possible to populate the keys while retaining the values?


  • Registered Users Posts: 159 ✭✭magooly


    Here is a working example that might get you a little further to where you want to go. Ive used your code where possible.

    Please read about how Maps work particularly when .hashcode() and .equals() is called on your key you place in the map.


    [HTML]
    package tmp;

    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Map;
    import java.util.Set;

    public class ListTest {

    Set<String> classList = new HashSet<String>(Arrays.asList("A", "B", "C", "D"));

    Map<String, String> packageList = new HashMap<String, String>();

    public void popMap() {
    for (String cl : classList) {
    packageList.put("Letter" + cl, cl);
    }
    }

    private void print() {
    System.out.print(packageList);
    }

    public static void main(String args[]) {
    ListTest l = new ListTest();
    l.popMap();
    l.print();
    }

    }[/HTML]


  • Registered Users Posts: 403 ✭✭counterpointaud


    @OP: Why are you using 4 calls to put() inside the loop? The key is the same for each call for each iteration.


  • Advertisement
  • Registered Users Posts: 3,793 ✭✭✭Hijpo


    @OP: Why are you using 4 calls to put() inside the loop? The key is the same for each call for each iteration.

    How I visualised the hash map being populated, going by .put() creating new pairs if the keys are not duplicates, i figured the variable cl holds a different value each time the loop iterates. when it populates the key using cl then I could hard code a value to each new key.

    Now that I've read what I was thinking I can understand why it wouldnt work and have slapped my face for it.


    @magooly, many thanks for taking the time to help to that level.


  • Registered Users Posts: 3,793 ✭✭✭Hijpo


    So i ended up with this.

    Converted the hashSet containing the class names to an array and created a second array with the package names in it.

    Then populated the hashMap using the elements of both arrays like this.
    private void createMappings()
        {
            int k = 0;
            int v = 0;
            
       
            do {
               classPackMap.put(classArray[k] , packageList[v]);
                  
               k++;
               v++;
               }
               
                  while ( v < 4);
                }
    

    It works and im happy i didnt straight up hard code the values in, i was this || close to giving in.

    Thanks again for the assistance!


  • Registered Users Posts: 223 ✭✭Fate Amenable To Change


    Jut to clarify a little in laymans term the way a hashmap works with the put id the first vlaue will be your key and then the second value will be what you want to store to that key.

    So the key could be like "fridaysBreakfeast"

    and the value associated could be "breakfeastRoll"

    so when you go looking for the value in the hashmap for "fridaysBreakfeast" it will return "breakfeastRoll"
    ////////////

    alternatively you could use the key ""mondaysLunch"
    and the value associated with this would "hamSandwich"
    so when you go looking for the value in the hashmap for "mondaysLunch" it will return "hamSandwich"


    The point being that rather than using numbers to find and store stuff you can sue a combination of letters and numbers.

    #################################################
    so using put

    yourArray.put("mondaysLunch", "hamSandwich");

    so everytime you look for mondaysLucbh it returns hamSandwich


  • Registered Users Posts: 3,793 ✭✭✭Hijpo


    Jut to clarify a little in laymans term the way a hashmap works with the put id the first vlaue will be your key and then the second value will be what you want to store to that key.

    So the key could be like "fridaysBreakfeast"

    and the value associated could be "breakfeastRoll"

    so when you go looking for the value in the hashmap for "fridaysBreakfeast" it will return "breakfeastRoll"
    ////////////

    alternatively you could use the key ""mondaysLunch"
    and the value associated with this would "hamSandwich"
    so when you go looking for the value in the hashmap for "mondaysLunch" it will return "hamSandwich"


    The point being that rather than using numbers to find and store stuff you can sue a combination of letters and numbers.

    #################################################
    so using put

    yourArray.put("mondaysLunch", "hamSandwich");

    so everytime you look for mondaysLucbh it returns hamSandwich

    Thanks for the info. U can follow the idea of creating pairs, I was just struggling with an efficient way of populating the hash map in the first place.


Advertisement