Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a hash table in Java?

Tags:

java

hashmap

hash

What is the most straightforward way to create a hash table (or associative array...) in Java? My google-fu has turned up a couple examples, but is there a standard way to do this?

And is there a way to populate the table with a list of key->value pairs without individually calling an add method on the object for each pair?

like image 307
akdom Avatar asked Aug 27 '08 01:08

akdom


People also ask

How do you create an empty hash table in Java?

Hashtable(): This creates an empty hashtable with the default load factor of 0.75 and an initial capacity is 11. Hashtable<K, V> ht = new Hashtable<K, V>(); Java.

What is a hash table Java?

A Hashtable is an array of a list. Each list is known as a bucket. The position of the bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key. Java Hashtable class contains unique elements.

How do you create a hash function in Java?

The idea is to make each cell of hash table point to a linked list of records that have same hash function value. Let's create a hash function, such that our hash table has 'N' number of buckets. To insert a node into the hash table, we need to find the hash index for the given key.


2 Answers

Map map = new HashMap();
Hashtable ht = new Hashtable();

Both classes can be found from the java.util package. The difference between the 2 is explained in the following jGuru FAQ entry.

like image 188
Edmund Tay Avatar answered Oct 09 '22 06:10

Edmund Tay


You can use double-braces to set up the data. You still call add, or put, but it's less ugly:

private static final Hashtable<String,Integer> MYHASH = new Hashtable<String,Integer>() {{
    put("foo",      1);
    put("bar",      256);
    put("data",     3);
    put("moredata", 27);
    put("hello",    32);
    put("world",    65536);
 }};
like image 36
izb Avatar answered Oct 09 '22 08:10

izb