PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Java · Theory

Java HashMap

← All stacks

Theory

205/270

Java HashMap

HashMap stores key → value, like a register: name → marks. You don’t scan the whole list to find Asha. You ask get("Asha"). Average lookup is very fast. Keys should be unique. Put the same key again and the old value is replaced.

Let’s take this on the board. HashMap<String, Integer> marks = new HashMap<>(); marks.put("Asha", 90); marks.put("Ravi", 70); print marks.get("Asha"); print marks.get("Neha");. Output: 90 then null. Neha was never put, so get returns null — not an exception. That null surprise fails viva if you don’t mention it.

Classic HashMap allows one null key and many null values. It is not synchronized. Hashtable is the old synchronized cousin — don’t pick Hashtable unless they ask. String keys are safe. If you use your own class as a key, hashCode and equals must be correct or lookup breaks.

Iterate with for (var e : marks.entrySet()) and print e.getKey() + "=" + e.getValue(). Don’t only memorise put/get. In a project, HashMap is the default map. Need insertion order? LinkedHashMap. Need sorted keys? TreeMap.

Diagram
put("Asha", 90)
  get("Asha") → 90
  get("Neha") → null
Exam tip

Say: key → value, put/get, average O(1). Then contrast Hashtable (synced, old) if asked.

Example

import java.util.HashMap;

// HashMap demo
public class Main {
  public static void main(String[] args) {
    HashMap<String, Integer> marks = new HashMap<>();
    marks.put("Asha", 90);
    marks.put("Ravi", 85);
    System.out.println(marks.get("Asha"));
  }
}

Java HashMap — output: 90. HashMap stores Asha→90, Ravi→85. get("Asha") looks up the key.

Short notes

  • DefHashMap = key → value. Fast lookup by key.
  • Ruleput(key, value), get(key). Unique keys. One null key allowed.
  • RememberNot synchronized. Iterate entrySet().
  • TrapBad hashCode/equals on custom keys. Don’t use Hashtable unless asked.

Questions

1

What does HashMap store?

2

How do you add and read?

3

Is HashMap synchronized?

Previous← Java Map InterfaceNextWorking of HashMap →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.