Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

size
hashtable
java

What is the Hashtable.size method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

A HashTable is a collection of key-value pairs. The Object used as a key should implement the hashCode & equals method. The key and the value should not be null.

You can read the difference between HashTable and HashMap here.

What is the size() method in Hashtable?

The size method of Hashtable returns the number of key-value mappings in the Hashtable object.

Syntax

public int size()

Parameter

This method does not take any parameters.

Return value

This method returns the integer value representing the number of key-value mappings.

Code

The example below shows the use of the size method:

import java.util.Hashtable;
class HashtableSizeExample {
public static void main( String args[] ) {
Hashtable<Integer, String> map = new Hashtable<>();
map.put(1, "one");
map.put(2, "two");
System.out.println("Hashtable is : " + map);
System.out.println("\nSize of the map is : " + map.size());
}
}

Explanation

In the code above:

  • In line 1, we import the Hashtable class.

  • From lines 4 to 6, we create a Hashtable object and use the put method to add two mappings({1=one, 2=two}) to the map.

  • In line 8, we use the size method to get the number of mappings present in the Hashtable object. We will get 2 as a result.

RELATED TAGS

size
hashtable
java

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring