0% found this document useful (0 votes)
3 views5 pages

Java Notes

The document provides a comprehensive guide to HashMap in Java, explaining its structure, functionality, and common methods. It includes examples of using HashMap to store student information and convert Roman numerals to integers, as well as comparisons with other data structures. Best practices for using HashMap are also discussed, emphasizing the importance of meaningful keys and efficient hash functions.

Uploaded by

sobhahitesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views5 pages

Java Notes

The document provides a comprehensive guide to HashMap in Java, explaining its structure, functionality, and common methods. It includes examples of using HashMap to store student information and convert Roman numerals to integers, as well as comparisons with other data structures. Best practices for using HashMap are also discussed, emphasizing the importance of meaningful keys and efficient hash functions.

Uploaded by

sobhahitesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

HashMap in Java: A Comprehensive Guide

Introduction
In Java, a HashMap is a data structure that stores key-value pairs in a
way that allows for efficient lookup, insertion, and deletion of
elements. It is a part of the Java Collections Framework and is widely
used in various applications.
What is a HashMap?
A HashMap is a hash table-based implementation of
the Map interface. It stores key-value pairs in an array, where each
key is unique and maps to a specific value. The keys are used to
identify the values, and the values can be retrieved using their
corresponding keys.
How HashMap Works
Here's a step-by-step explanation of how a HashMap works:
1. Key-Value Pairs: When you add a key-value pair to
a HashMap, the key is hashed using a hash function. The hash
function generates a hash code, which is an integer value that
represents the key.
2. Index Calculation: The hash code is then used to calculate the
index at which the key-value pair should be stored in the
underlying array.
3. Collision Resolution: If two keys hash to the same index, a
collision occurs. To resolve collisions, HashMap uses a
technique called chaining, where each index in the array points
to a linked list of key-value pairs that hash to that index.
4. Lookup: When you retrieve a value from a HashMap using its
key, the key is hashed, and the resulting hash code is used to
calculate the index at which the key-value pair is stored.
The HashMap then traverses the linked list at that index to find
the key-value pair.
HashMap Methods
Here are some common methods used with HashMap:
 put(K key, V value): Adds a key-value pair to the HashMap.
 get(Object key): Retrieves the value associated with the
specified key.
 containsKey(Object key): Returns true if
the HashMap contains the specified key.
 containsValue(Object value): Returns true if
the HashMap contains the specified value.
 remove(Object key): Removes the key-value pair associated
with the specified key.
 clear(): Removes all key-value pairs from the HashMap.
 size(): Returns the number of key-value pairs in the HashMap.
HashMap Example
Here's an example of using a HashMap to store student information:
Java
import java.util.HashMap;

public class Student {


private String name;
private int age;

public Student(String name, int age) {


this.name = name;
this.age = age;
}

public String getName() {


return name;
}

public int getAge() {


return age;
}
}
public class Main {
public static void main(String[] args) {
HashMap<String, Student> students = new HashMap<>();

// Add students to the HashMap


students.put("John", new Student("John", 20));
students.put("Alice", new Student("Alice", 22));
students.put("Bob", new Student("Bob", 21));

// Retrieve a student's information


Student student = students.get("John");
System.out.println("Name: " + student.getName() + ", Age: " +
student.getAge());

// Remove a student from the HashMap


students.remove("Bob");

// Check if a student exists in the HashMap


if (students.containsKey("Alice")) {
System.out.println("Alice is in the HashMap");
}
}
}

Output  Name: John, Age: 20


Alice is in the HashMap

Second example ::::::::::


import java.util.HashMap;

public class A {
public static void main(String[] args) {
String roman = "MCMXCIV"; // Example Roman numeral
int result = romanToInt(roman);
System.out.println("The integer value of " + roman + " is: " +
result);
}

public static int romanToInt(String s) {


HashMap<Character, Integer> romanMap = new HashMap<>();
romanMap.put('I', 1);
romanMap.put('V', 5);
romanMap.put('X', 10);
romanMap.put('L', 50);
romanMap.put('C', 100);
romanMap.put('D', 500);
romanMap.put('M', 1000);

int total = 0;//1996


int prevValue = 0;//100
System.out.println(romanMap.size());//7
for (int i = s.length() - 1; i >= 0; i--) {
char currentChar = s.charAt(i);
int currentValue = romanMap.get(currentChar);

if (currentValue < prevValue) {


total -= currentValue; // Subtract if the current value
is less than the previous value
} else {
total += currentValue; // Add otherwise
}
prevValue = currentValue; // Update the previous value
}

return total;
}
}

Output  7
The integer value of MCMXCIV is: 1994
------------------------------------------------------------------------------------
HashMap vs. Other Data Structures
Here's a comparison of HashMap with other data structures:
 ArrayList: HashMap is more efficient than ArrayList for
lookup and insertion operations, especially for large datasets.
However, ArrayList is more suitable for sequential access and
modification of elements.
 TreeMap: TreeMap is a sorted map implementation that
provides faster lookup and insertion operations
than HashMap for sorted data. However, TreeMap is slower
than HashMap for unsorted data.
 HashSet: HashSet is a set implementation that provides faster
lookup and insertion operations than HashMap for unique
elements. However, HashSet does not store values associated
with keys.
Best Practices for Using HashMap
Here are some best practices for using HashMap:
 Use meaningful keys: Choose keys that are meaningful and
easy to understand.
 Avoid null keys: Avoid using null keys, as they can
cause NullPointerExceptions.
 Use efficient hash functions: Use efficient hash functions to
minimize collisions and improve performance.
 Monitor performance: Monitor the performance of
your HashMap and adjust its capacity and load factor
accordingly.
------------------------------------------------------------------------------------
PALINDROME example problem:
class A{
// public static void main(String[] args) {
// int x=121;
// int reverse=0;
// int total=x;
// while(total!=0){
// int digit=(int)(total % 10);
// reverse= (reverse * 10) + digit;
// total=total/10;
// }
// if(reverse == x){
// System.out.println("palindrome reverse"+ reverse +"X:"+
x);
// }else{
// System.out.println("not palindrome");
// }
// }
// }
Output: palindrome reverse 121 X: 121

You might also like