Monday, 2 February 2026

Simple Hashtable program with example for handling Products

HashTable class enables mapping keys to values, any non-null object is a candidate to be used as a key or a value.

Below provided is a basic program illustrating how a HashTable is used, how key/ value pairs values are inserted, how a particular value is retrieved using key, how a pair is removed using key and how a pair is updated.

import java.util.Hashtable;

class Product {

long id;

String name;

public Product(long id, String name) {

super();

this.id = id;

this.name = name;

}

@Override

public String toString() {

return "Product [id=" + id + ", name=" + name + "]";

}


public long getId() {

return id;

}

public void setId(long id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}


public class ProductHashTable {


public static void main(String[] args) {

Hashtable<Long, Product> productHash = new Hashtable<>();

productHash.put(11L, new Product(1, "Trimmer"));

productHash.put(22L, new Product(2, "Nail Cutter"));

productHash.put(33L, new Product(3, "Smartphone"));

System.out.println(productHash.get(22L)); // getting specific product by key

System.out.println(productHash); // printing all products

productHash.remove(11L); //removing specific record using hash key

productHash.put(33L, new Product(4, "Umbrella")); //updating hash record

System.out.println(productHash);

}


}


No comments:

Post a Comment