Java - Append key value pairs to hash table

by
Jeremy Canfield |
Updated: August 25 2022
| Java articles
Here is an example of how to create three different empty hash tables, one that will contain objects, another for integers, and another for booleans.
public class Main {
public static void main(String[] args){
Hashtable<String, Object> objecthashtable = new Hashtable<String, Object>();
Hashtable<String, Integer> integerhashtable = new Hashtable<String, Integer>();
Hashtable<String, Boolean> booleanhashtable = new Hashtable<String, Boolean>();
System.out.println("object hash table = " + objecthashtable);
System.out.println("integer hash table = " + integerhashtable);
System.out.println("boolean hash table = " + booleanhashtable);
}
}
In this example, System.out.println will just return { }, since each hash table is empty (contains no key value pairs).
object hash table = {}
integer hash table = {}
boolean hash table = {}
And here is how you would append key value pairs to each hash table.
public class Main {
public static void main(String[] args){
Hashtable<String, Object> objecthashtable = new Hashtable<String, Object>();
Hashtable<String, Integer> integerhashtable = new Hashtable<String, Integer>();
Hashtable<String, Boolean> booleanhashtable = new Hashtable<String, Boolean>();
objecthashtable.put("foo", "Hello");
objecthashtable.put("bar", "World");
integerhashtable.put("foo", 0);
integerhashtable.put("bar", 1);
booleanhashtable.put("foo", true);
booleanhashtable.put("bar", false);
System.out.println("object hash table = " + objecthashtable);
System.out.println("integer hash table = " + integerhashtable);
System.out.println("boolean hash table = " + booleanhashtable);
}
}
Now System.out.println should return key value pairs.
object hash table = {bar=World, foo=Hello}
integer hash table = {bar=1, foo=0}
boolean hash table = {bar=false, foo=true}
Did you find this article helpful?
If so, consider buying me a coffee over at