0% found this document useful (0 votes)
8 views

Hashtable in Java - GeeksforGeeks

Uploaded by

Muhammad Huzaifa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Hashtable in Java - GeeksforGeeks

Uploaded by

Muhammad Huzaifa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Sign in to GeeksforGeeks with Google

Data Structures Algorithms Interview Preparation Topic-wise Practice C++ Java Python C
Imran Wahab
imran.sargodha@gmail.com

Hashtable in Java IT department Govt ambala muslim graduate


college
it.gamgc@gmail.com

Difficulty Level : Medium ● Last Updated : 11 May, 2022

The Hashtable class implements a hash table, which maps keys to values. Any non-null

object can be used as a key or as a value. To successfully store and retrieve objects from

a hashtable, the objects used as keys must implement the hashCode method and the

equals method.

Features of Hashtable

It is similar to HashMap, but is synchronized.

Hashtable stores key/value pair in hash table.

In Hashtable we specif y an object that is used as a key, and the value we want to

associate to that key. The key is then hashed, and the resulting hash code is used as

the index at which the value is stored within the table.

The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.

HashMap doesn’t provide any Enumeration, while Hashtable provides not fail-fast

We use cookies to ensure you have the best browsing experience on our website. By using our
Got It !
site, Enumeration.
you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Start Your Coding Journey Now! Sign in to GeeksforGeeks
Declaration:

Login Register
with Google
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Clo

Imran Wahab
imran.sargodha@gmail.com
Type Parameters :

IT department Govt ambala muslim graduate


K – the type of keys maintained by this map
college
it.gamgc@gmail.com
V – the type of mapped values

The Hierarchy of Hashtable

Hashtable implements Serializable, Cloneable, Map<K,V> inter faces and extends

Dictionar y<K,V>. The direct subclasses are Proper ties, UIDefaults.

Constructors :

In order to create a Hashtable, we need to impor t it from java.util.Hashtable. There are

various ways in which we can create a Hashtable.

We
1. use cookies to ensure
Hashtable(): you have
This the best
creates an browsing
empty experience
hashtableon ourwith
website.
theBy default
using our load factor of 0.75 and
Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
an initial capacity is 11.
Start Your Coding Journey Now! Sign in to GeeksforGeeks
Login
Hashtable<K, V> ht = new Hashtable<K, V>();
Register
with Google

Imran Wahab
imran.sargodha@gmail.com

Java

IT department Govt ambala muslim graduate


college
it.gamgc@gmail.com
// Java program to demonstrate
// adding elements to Hashtable

import java.io.*;
import java.util.*;

class AddElementsToHashtable {
public static void main(String args[])
{
// No need to mention the
// Generic type twice
Hashtable<Integer, String> ht1 = new Hashtable<>();

// Initialization of a Hashtable
// using Generics
Hashtable<Integer, String> ht2
= new Hashtable<Integer, String>();

// Inserting the Elements


// using put() method
ht1.put(1, "one");
ht1.put(2, "two");
ht1.put(3, "three");

ht2.put(4, "four");
ht2.put(5, "five");
ht2.put(6, "six");

// Print mappings to the console


System.out.println("Mappings of ht1 : " + ht1);
System.out.println("Mappings of ht2 : " + ht2);
}
}

Output

Mappings of ht1 : {3=three, 2=two, 1=one}


We use cookies to ensure you have the best browsing experience on our website. By using our
Got It !
Mappings
site, of ht2
you acknowledge : have
that you {6=six,
read and5=five, 4=four}
understood our Cookie Policy & Privacy Policy
2.
Start Your Coding Journey Now! Sign in to GeeksforGeeks
Hashtable(int initialCapacity):
Login This
Register
creates

with Google
a hash table that has an initial size

specified by initialCapacity and the default load factor is 0.75.

Imran Wahab
Hashtable<K, V> ht = new Hashtable<K, V>(int initialCapacity);imran.sargodha@gmail.com

IT department Govt ambala muslim graduate


college
it.gamgc@gmail.com

Java

// Java program to demonstrate


// adding elements to Hashtable

import java.io.*;
import java.util.*;

class AddElementsToHashtable {
public static void main(String args[])
{
// No need to mention the
// Generic type twice
Hashtable<Integer, String> ht1 = new Hashtable<>(4);

// Initialization of a Hashtable
// using Generics
Hashtable<Integer, String> ht2
= new Hashtable<Integer, String>(2);

// Inserting the Elements


// using put() method
ht1.put(1, "one");
ht1.put(2, "two");
ht1.put(3, "three");

ht2.put(4, "four");
ht2.put(5, "five");
ht2.put(6, "six");

// Print mappings to the console


System.out.println("Mappings of ht1 : " + ht1);
System.out.println("Mappings of ht2 : " + ht2);
}
}

We use cookies to ensure you have the best browsing experience on our website. By using our
Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Start Your Coding Journey Now! Sign in to GeeksforGeeks
Output

Login Register
Mappings of ht1 : {3=three, 2=two, 1=one} with Google

Mappings of ht2 : {4=four, 6=six, 5=five}


Imran Wahab
imran.sargodha@gmail.com
3. Hashtable(int size, float fillRatio): This version creates a hash table that has an initial

IT department Govt ambala muslim graduate


size specified by size and fill ratio specified by fillRatio. fill ratio: Basically, it determines

college
it.gamgc@gmail.com
how full a hash table can be before it is resized upward and its Value lies between 0.0 to

1.0.

Hashtable<K, V> ht = new Hashtable<K, V>(int size, float fillRatio);

Java

// Java program to demonstrate


// adding elements to Hashtable

import java.io.*;
import java.util.*;

class AddElementsToHashtable {
public static void main(String args[])
{
// No need to mention the
// Generic type twice
Hashtable<Integer, String> ht1
= new Hashtable<>(4, 0.75f);

// Initialization of a Hashtable
// using Generics
Hashtable<Integer, String> ht2
= new Hashtable<Integer, String>(3, 0.5f);

// Inserting the Elements


// using put() method
ht1.put(1, "one");
ht1.put(2, "two");
ht1.put(3, "three");

ht2.put(4, "four");
ht2.put(5,
We use cookies "five");
to ensure you have the best browsing experience on our website. By using our
Got It !
ht2.put(6,
site, you acknowledge that you"six");
have read and understood our Cookie Policy & Privacy Policy
Start Your Coding
// Print mappings Journey Now! : " in+ toht1);
to the console
System.out.println("Mappings of ht1 Sign
Login Register
GeeksforGeeks with Google
System.out.println("Mappings of ht2 : " + ht2);
}
} Imran Wahab
imran.sargodha@gmail.com

IT department Govt ambala muslim graduate


Output
college
it.gamgc@gmail.com

Mappings of ht1 : {3=three, 2=two, 1=one}


Mappings of ht2 : {6=six, 5=five, 4=four}

4. Hashtable(Map<? extends K,? extends V> m): This creates a hash table that is

initialized with the elements in m.

Hashtable<K, V> ht = new Hashtable<K, V>(Map m);

Java

// Java program to demonstrate


// adding elements to Hashtable

import java.io.*;
import java.util.*;

class AddElementsToHashtable {
public static void main(String args[])
{
// No need to mention the
// Generic type twice
Map<Integer, String> hm = new HashMap<>();

// Inserting the Elements


// using put() method
hm.put(1, "one");
hm.put(2, "two");
hm.put(3, "three");

// Initialization of a Hashtable
// using Generics
We use cookies to ensure you have the best browsing experience on our website. By using our
Hashtable<Integer, String> ht2 Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
= new Hashtable<Integer, String>(hm);
Start Your Coding
// Print mappings Journey Now! Sign in to GeeksforGeeks
to the console Login Register
with Google
System.out.println("Mappings of ht2 : " + ht2);
}
Imran Wahab
}
imran.sargodha@gmail.com

IT department Govt ambala muslim graduate


Output
college
it.gamgc@gmail.com

Mappings of ht2 : {3=three, 2=two, 1=one}

Example :

Java

// Java program to illustrate


// Java.util.Hashtable

import java.util.*;

public class GFG {


public static void main(String[] args)
{
// Create an empty Hashtable
Hashtable<String, Integer> ht = new Hashtable<>();

// Add elements to the hashtable


ht.put("vishal", 10);
ht.put("sachin", 30);
ht.put("vaibhav", 20);

// Print size and content


System.out.println("Size of map is:- " + ht.size());
System.out.println(ht);

// Check if a key is present and if


// present, print value
if (ht.containsKey("vishal")) {
Integer a = ht.get("vishal");
System.out.println("value for key"
+ " \"vishal\" is:- " + a);
}
}
}
We use cookies to ensure you have the best browsing experience on our website. By using our
Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Start Your Coding Journey Now! Sign in to GeeksforGeeks
Login Register
with Google

Output

Imran Wahab
Size of map is:- 3 imran.sargodha@gmail.com

{vaibhav=20, vishal=10, sachin=30}


IT department Govt ambala muslim graduate
value for key "vishal" is:- 10 college
it.gamgc@gmail.com

Per forming Various Operations on Hashtable

1. Adding Elements : In order to add an element to the hashtable, we can use the put()

method. However, the inser tion order is not retained in the hashtable. Internally, for

ever y element, a separate hash is generated and the elements are indexed based on this

hash to make it more efficient.

Java

// Java program to demonstrate


// adding elements to Hashtable

import java.io.*;
import java.util.*;

class AddElementsToHashtable {
public static void main(String args[])
{
// No need to mention the
// Generic type twice
Hashtable<Integer, String> ht1 = new Hashtable<>();

// Initialization of a Hashtable
// using Generics
Hashtable<Integer, String> ht2
= new Hashtable<Integer, String>();

// Inserting the Elements


// using put() method
ht1.put(1, "Geeks");
ht1.put(2, "For");
ht1.put(3, "Geeks");
We use cookies to ensure you have the best browsing experience on our website. By using our
ht2.put(1, "Geeks"); Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
ht2.put(2, "For");
ht2.put(3, "Geeks");
Start Your Coding Journey Now! Login Register
// Print mappings to the console Sign in to GeeksforGeeks with Google
System.out.println("Mappings of ht1 : " + ht1);
System.out.println("Mappings of ht2 : " + ht2);
Imran Wahab
}
imran.sargodha@gmail.com
}

IT department Govt ambala muslim graduate


college
it.gamgc@gmail.com

Output

Mappings of ht1 : {3=Geeks, 2=For, 1=Geeks}


Mappings of ht2 : {3=Geeks, 2=For, 1=Geeks}

2. Changing Elements : Af ter adding the elements if we wish to change the element, it

can be done by again adding the element with the put() method. Since the elements in

the hashtable are indexed using the keys, the value of the key can be changed by simply

inser ting the updated value for the key for which we wish to change.

Java

// Java program to demonstrate


// updating Hashtable

import java.io.*;
import java.util.*;
class UpdatesOnHashtable {
public static void main(String args[])
{

// Initialization of a Hashtable
Hashtable<Integer, String> ht
= new Hashtable<Integer, String>();

// Inserting the Elements


// using put method
ht.put(1, "Geeks");
ht.put(2, "Geeks");
ht.put(3, "Geeks");

// print initial map to the console


System.out.println("Initial Map " on
We use cookies to ensure you have the best browsing experience + our
ht);website. By using our
Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
// Update the value at key 2
Start Your Coding Journey Now! Sign in to GeeksforGeeks
ht.put(2, "For"); Login Register
with Google
// print the updated map
System.out.println("Updated Map " + ht);
Imran Wahab
}
imran.sargodha@gmail.com
}

IT department Govt ambala muslim graduate


college
it.gamgc@gmail.com

Output

Initial Map {3=Geeks, 2=Geeks, 1=Geeks}


Updated Map {3=Geeks, 2=For, 1=Geeks}

3. Removing Element : In order to remove an element from the Map, we can use the

remove() method. This method takes the key value and removes the mapping for a key

from this map if it is present in the map.

Java

// Java program to demonstrate


// the removing mappings from Hashtable

import java.io.*;
import java.util.*;
class RemovingMappingsFromHashtable {

public static void main(String args[])


{
// Initialization of a Hashtable
Map<Integer, String> ht
= new Hashtable<Integer, String>();

// Inserting the Elements


// using put method
ht.put(1, "Geeks");
ht.put(2, "For");
ht.put(3, "Geeks");
ht.put(4, "For");

// Initial HashMap
System.out.println("Initial map : " + ht);
We use cookies to ensure you have the best browsing experience on our website. By using our
Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
// Remove the map entry with key 4
ht.remove(4);
Start Your Coding Journey Now! Sign in to GeeksforGeeks
// Final Hashtable
Login Register
with Google
System.out.println("Updated map : " + ht);
}
} Imran Wahab
imran.sargodha@gmail.com

IT department Govt ambala muslim graduate


Output
college
it.gamgc@gmail.com

Initial map : {4=For, 3=Geeks, 2=For, 1=Geeks}


Updated map : {3=Geeks, 2=For, 1=Geeks}

4. Traversal of a Hashtable : To iterate the table, we can make use of an advanced for

loop. Below is the example of iterating a hashtable.

Java

// Java program to illustrate


// traversal of Hashtable

import java.util.Hashtable;
import java.util.Map;

public class IteratingHashtable {


public static void main(String[] args)
{
// Create an instance of Hashtable
Hashtable<String, Integer> ht = new Hashtable<>();

// Adding elements using put method


ht.put("vishal", 10);
ht.put("sachin", 30);
ht.put("vaibhav", 20);

// Iterating using enhanced for loop


for (Map.Entry<String, Integer> e : ht.entrySet())
System.out.println(e.getKey() + " "
+ e.getValue());
}
}

We use cookies to ensure you have the best browsing experience on our website. By using our
Output
Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Start Your Coding Journey Now! Sign in to GeeksforGeeks
vaibhav 20 Login Register
with Google
vishal 10
sachin 30
Imran Wahab
imran.sargodha@gmail.com

Internal Working of Hashtable

IT department Govt ambala muslim graduate


college
it.gamgc@gmail.com
Hashtable datastructure is an array of buckets which stores the key/value pairs in them.

It makes use of hashCode() method to determine which bucket the key/value pair

should map.

The hash function helps to determine the location for a given key in the bucket list.

Generally, hashcode is a non-negative integer that is equal for equal Objects and may or

may not be equal for unequal Objects. To determine whether two objects are equal or

not, hashtable makes use of the equals() method.

It is possible that two unequal Objects have the same hashcode. This is called a

collision. To resolve collisions, hashtable uses an array of lists. The pairs mapped to a

single bucket (array index) are stored in a list and list reference is stored in the array

index.

Methods of Hashtable

We use cookies to ensure you have the best browsing experience on our website. By using our
Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Start Your Coding Journey Now! Sign in to GeeksforGeeks
K – The type of the keys in the map.

Login
V – The type of values mapped in the map.
Register
with Google

Imran Wahab
ME THOD DESCRIPTION
imran.sargodha@gmail.com

IT department Govt ambala muslim graduate


clear() Clears this hashtable so that it contains no keys.
college
it.gamgc@gmail.com

clone() Creates a shallow copy of this hashtable.

compute(K key, Attempts to compute a mapping for the specified key and

BiFunction<? super its current mapped value (or null if there is no current

mapping).
K,? super V,? extends V>

remappingFunction)

computeIfA bsent(K key, If the specified key is not already associated with a value

Function<? super K,? (or is mapped to null), attempts to compute its value using

the given mapping function and enters it into this map


extends V>

unless null.
mappingFunction)

computeIfPresent(K key, If the value for the specified key is present and non-null,

BiFunction<? super K,? attempts to compute a new mapping given the key and its

super V,? extends V> current mapped value.

remappingFunction)

contains(Object value) Tests if some key maps into the specified value in this

hashtable.

containsKey(Object key) Tests if the specified object is a key in this hashtable.

containsValue(Object Returns true if this hashtable maps one or more keys to

value) this value.

We use cookies to ensure you have the best browsing experience on our website. By using our
Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Start Your Coding Journey Now! Sign in to GeeksforGeeks
ME THOD
Login Register
with Google
DESCRIPTION

elements() Returns an enumeration of the values in this hashtable.


Imran Wahab
imran.sargodha@gmail.com

entr ySet() Returns a Set view of the mappings contained in this map.

IT department Govt ambala muslim graduate


college
it.gamgc@gmail.com
equals(Object o) Compares the specified Object with this Map for equality,

as per the definition in the Map inter face.

get(Object key) Returns the value to which the specified key is mapped, or

null if this map contains no mapping for the key.

hashCode() Returns the hash code value for this Map as per the

definition in the Map inter face.

isEmpty() Tests if this hashtable maps no keys to values.

keys() Returns an enumeration of the keys in this hashtable.

keySet() Returns a Set view of the keys contained in this map.

merge(K key, V value, If the specified key is not already associated with a value

BiFunction<? super V,? or is associated with null, associates it with the given non-

super V,? extends V> null value.

remappingFunction)

put(K key, V value) Maps the specified key to the specified value in this

hashtable.

putAll(Map<? extends K,? Copies all of the mappings from the specified map to this

extends V> t) hashtable.

We use cookies to ensure you have the best browsing experience on our website. By using our
Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Start Your Coding Journey Now! Sign in to GeeksforGeeks
ME THOD
Login Register
with Google
DESCRIPTION

rehash() Increases the capacity of and internally reorganizes this


Imran Wahab
imran.sargodha@gmail.com
hashtable, in order to accommodate and access its entries

more efficiently.

IT department Govt ambala muslim graduate


college
it.gamgc@gmail.com
remove​
(Object key) Removes the key (and its corresponding value) from this

hashtable.

size() Returns the number of keys in this hashtable.

toString() Returns a string representation of this Hashtable object in

the form of a set of entries, enclosed in braces and

separated by the A SCII characters “, ” (comma and space).

values() Returns a Collection view of the values contained in this

map.

Methods declared in inter face java.util.Map

ME THOD DESCRIPTION

forEach(BiConsumer<? Per forms the given action for each entr y in this map until all

super K,? super V> entries have been processed or the action throws an

action) exception.

getOrDefault(Object Returns the value to which the specified key is mapped, or

key, V defaultValue) defaultValue if this map contains no mapping for the key.

putIfA bsent​
(K key, V If the specified key is not already associated with a value (or

value) is mapped to null) associates it with the given value and

returns null, else returns the current value.

We use cookies to ensure you have the best browsing experience on our website. By using our
Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Start Your Coding Journey Now! Sign in to GeeksforGeeks
ME THOD
Login Register
with Google
DESCRIPTION

remove​
(Object key, Removes the entr y for the specified key only if it is currently
Imran Wahab
imran.sargodha@gmail.com
mapped to the specified value.
Object value)

IT department Govt ambala muslim graduate


college
it.gamgc@gmail.com
replace(K key, V value) Replaces the entr y for the specified key only if it is currently

mapped to some value.

replace(K key, V Replaces the entr y for the specified key only if currently

oldValue, V newValue) mapped to the specified value.

replaceAll(BiFunction<? Replaces each entr y ’s value with the result of invoking the

super K,? super V,? given function on that entr y until all entries have been

extends V> function) processed or the function throws an exception.

Must Read:

Differences between HashMap and HashTable in Java

Reference :

https://doc s.oracle.com/en/java/javase/11/doc s/api/java.base/java/util/Hashtable.ht

ml

Like 50

We use cookies to ensure you have the best browsing experience on our website. By using our
Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Start Your Coding Journey Now! Sign in to GeeksforGeeks
Previous Next
Login Register
with Google

Imran Wahab
imran.sargodha@gmail.com

IT department Govt ambala muslim graduate


college
it.gamgc@gmail.com

RECOMMENDED ARTICLES Page : 1 2 3

Differences between HashMap and Hashtable containsValue() Method


01 05
HashTable in Java in Java
20, Aug 15 26, Jun 18

Hashtable toString() Method in Java Hashtable containsKey() Method in


02 06
26, Jun 18
Java
26, Jun 18

Hashtable elements() Method in


03
Java Hashtable put() Method in Java
26, Jun 18
07 26, Jun 18

Hashtable keys() Method in Java Hashtable get() Method in Java


04 26, Jun 18
08 26, Jun 18

We use cookies to ensure you have the best browsing experience on our website. By using our
Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Start Your Coding Journey Now! Sign in to GeeksforGeeks
Ar ticle Contributed By :

Login Register
with Google
GeeksforGeeks
Imran Wahab
imran.sargodha@gmail.com

Vote for difficulty IT department Govt ambala muslim graduate


Current difficulty : Medium college
it.gamgc@gmail.com

Easy Normal Medium Hard Expert

Improved By : OwiesAAlomari, nidhi_biet, bishnoisunil007, Ganeshchowdharysadanala

Article Tags : HashTable, Java - util package, Java-Collections, Java-HashTable, Java

Practice Tags : Java, Java-Collections

Improve Article Report Issue

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.

Load Comments

A-143, 9th Floor, Sovereign Corporate Tower,


Sector-136, Noida, Uttar Pradesh - 201305
feedback@geeksforgeeks.org

We use cookies to ensure you have the best browsing experience on our website. By using our
Got It !
Company
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Learn
About Us Algorithms
Start Your Coding Journey Now! Sign in to GeeksforGeeks
Login Register
Careers with Google Data Structures
In Media SDE Cheat Sheet
Imran Wahab
Contact Us Machine learning
imran.sargodha@gmail.com

Privacy Policy CS Subjects


IT department Govt ambala muslim graduate
Copyright Policy college Video Tutorials
it.gamgc@gmail.com
Courses

News Languages
Python
Top News
Java
Technology
CPP
Work & Career
Golang
Business
C#
Finance
SQL
Lifestyle
Kotlin
Knowledge

Web Development Contribute


Web Tutorials Write an Article
Django Tutorial Improve an Article
HTML Pick Topics to Write
JavaScript Write Interview Experience
Bootstrap Internships
ReactJS Video Internship
NodeJS

@geeksforgeeks , Some rights reserved

We use cookies to ensure you have the best browsing experience on our website. By using our
Got It !
site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

You might also like