CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2010
    Posts
    161

    Arraylist and Hashmap now working properly

    Hi

    I have this annoying problem and I can't get my head around it.

    basically I have an Arraylist with around 200 values in it.

    But when I pass the value to a Hashmap only 80 are stored.

    This is the syntax I am using for it :

    Code:
    ArrayList<String> as = new ArrayList<String>();
    
               while(st.hasMoreTokens()){
                   as.add(st.nextToken());
               }
           System.out.println("The size of the ArrayList as is : " + as.size());
    
           HashMap<String,Integer> map =new HashMap<String, Integer>();
    
    
    
           for(int s=0;s<as.size();s++){
               map.put(as.get(s),1);  
           }
           System.out.println("The size of map : " + map.size()); // not all the values from the arraylist are stored

    Can someone tell me what I am doing wrong? thank you

  2. #2
    Join Date
    May 2009
    Location
    Lincs, UK
    Posts
    298

    Re: Arraylist and Hashmap now working properly

    That depends on what strings the st.nextToken() method is returning. If these strings can repeat, ArrayList will load them as different elements, but when you put these duplicates in the HashMap they will be all loaded as the same element in the map replacing any existing value (in your case with the same Integer 1).

    Before putting a new pair in the map you can check is the key has already been put with the containsKey(key) method.

  3. #3
    Join Date
    Jan 2010
    Posts
    161

    Re: Arraylist and Hashmap now working properly

    it makes sense, I think that's exactly what's happening because what I am storing in the map are words and some of them are repeating words.

    Thank you

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured