4

My simple java code looks like below:

String s1 = "FB";

String s2 = "Ea";

System.out.println(s1.hashCode() == s2.hashCode()); // true

Map<String, Integer> map = new HashMap<>();

map.put(s1, 1);

map.put(s2, 2);

While debugging this piece of code in IntelliJIdea, I am not able see the linked list created by HashMap data structure, also, it is creating two buckets instead of one though hashcode is same for s1 and s2. Could you please provide clarity on this?

GBlodgett
  • 12,704
  • 4
  • 31
  • 45
Purushotham CK
  • 425
  • 6
  • 8
  • Does HashMap use a linked list approach for collisions? I thought it used open addressing with a fallback to a tree structure in Java 8 and newer. – Daniel Pryden Aug 14 '18 at 13:30
  • 1
    Perhaps more importantly: why does it matter? What observable behavior are you seeing? – Daniel Pryden Aug 14 '18 at 13:31
  • 1
    @DanielPryden it will switch to a tree under some conditions, but starts with a linked list https://stackoverflow.com/questions/47921663/when-and-how-does-hashmap-convert-the-bucket-from-linked-list-to-red-black-trees/47922079#47922079 – Eugene Aug 14 '18 at 13:48

2 Answers2

13

IDEA has simplified view for maps by default. To see all inner fields you need to Right click on map object, then View as -> Object, then do the same with HashMap$Node object.

enter image description here

Regarding table size, it has 16 buckets by default:

java.util.HashMap#DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

esin88
  • 3,091
  • 30
  • 35
  • 1
    thanks. Still i couldn't see hash and next values inside object view. I'm using IntelliJIdea Community 2018.1 version. – Purushotham CK Aug 15 '18 at 15:59
  • Is it possible to make it show maps as objects by default, without right clicking it? – 阿尔曼 Oct 10 '20 at 13:12
  • 2
    @阿尔曼, yes, in `Settings` | `Build, Execution, Deployment` | `Debugger` | `Data Views` | `Java` you need to uncheck `Enable alternative view for Collection classes` – esin88 Oct 12 '20 at 12:31
8

You need to do three things. It's not straight forward, it took me a while to figure it out since nobody has answered it before.

You need to uncheck that value if it is checked. To open that window you need to right click inside the debugger then chose "Customize Data Views..." You need to uncheck that value if it is checked. To open that window you need to right click inside the debugger then chose "Customize Data Views..."

Now you should see a list inside that table.

Second, you need to right click on the node that you want to see the next node on it and chose "new class level watch"

Second you need to right click on the node that you want to see the next node on it and chose "new class level watch"

right click on that node and chose putMapEntries(); right click on that node and chose putMapEntries();

As you can see the next value for FB is Ea As you can see the next value for  FB is Ea

I hope that helped.

JS Lover
  • 622
  • 5
  • 16