Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap contains 4 elements but only 3 are shown in debug

Tags:

java

hashmap

I have defined an HashMap with the following code:

final Map<OrderItemEntity, OrderItemEntity> savedOrderItems = new HashMap<OrderItemEntity, OrderItemEntity>();
final ListIterator<DiscreteOrderItemEntity> li = ((BundleOrderItemEntity) oi).getDiscreteOrderItems().listIterator();

while (li.hasNext()) {
    final DiscreteOrderItemEntity doi = li.next();
    final DiscreteOrderItemEntity savedDoi = (DiscreteOrderItemEntity) orderItemService.saveOrderItem(doi);
    savedOrderItems.put(doi, savedDoi);
    li.remove();
}

((BundleOrderItemEntity) oi).getDiscreteOrderItems().addAll(doisToAdd);
final BundleOrderItemEntity savedBoi = (BundleOrderItemEntity) orderItemService.saveOrderItem(oi);
savedOrderItems.put(oi, savedBoi);

I put 4 items into the HashMap. When I debug, even if the size is 4, it only shows 3 elements:

debugging session

This is the list of the elements it contains.

{DiscreteOrderItemEntity@1c29ef3c=DiscreteOrderItemEntity@41949d95, DiscreteOrderItemEntity@2288b93c=DiscreteOrderItemEntity@2288b93c, BundleOrderItemEntity@1b500292=BundleOrderItemEntity@d0f29ce5, DiscreteOrderItemEntity@9203174a=DiscreteOrderItemEntity@9203174a}

What can be the problem?

like image 632
Saurabh Kumar Avatar asked Jul 21 '15 08:07

Saurabh Kumar


1 Answers

Hashmaps handle collisions.

Since your HashMap is composed by only 16 buckets, the hash of the element must be reduced to a number that spans between 0 and 15 (e.g. hash % 16). So two elements may be in the same bucket (the same HashMapNode).

You can inspect each HashMapNode to find out which one contains two elements.

like image 80
enrico.bacis Avatar answered Oct 04 '22 21:10

enrico.bacis