Codebox
Codebox

Reputation: 87

Iterating hashmap, using keyset/entryset

I'm trying to access the stuff I put in my hashmap, but it's not working. Apparently the iterator for hashmap doesnt have anything. It cant do a mapIter.hasNext(), it'll be false.

Here's the code:

    Iterator<Product> cIter = getCartContent(cart).iterator();
    HashMap<Product, Integer> hash = new HashMap<Product, Integer>();
    Iterator<Product> mIter = hash.keySet().iterator();

    Product p;

    while(cIter.hasNext()) {
        p = cIter.next();

        if(hash.containsKey(p))
            hash.put(p, hash.get(p) + 1);
        else
            hash.put(p, 1);

    }

    if(!mIter.hasNext())
        System.out.println("Empty mIter");

Upvotes: 0

Views: 1310

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279940

When you call

HashMap<Product, Integer> hashmap = new HashMap<Product, Integer>();
Iterator<Product> mapIter = hashmap.keySet().iterator();

The Iterator that is created has a view of the empty HashMap, because you have yet to add anything to it. When you call hasNext(), even if the HashMap itself contains elements, the Iterator's view doesn't see it.

Create the Iterator when you absolutely need it, not before, ie. right before you call hasNext() in your code.

Iterator<Product> mapIter = hashmap.keySet().iterator();

if(!mapIter.hasNext())
    System.out.println("Empty mapIter");

Upvotes: 1

Related Questions