Skip to content

Instantly share code, notes, and snippets.

@retran
Created April 17, 2017 11:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save retran/c92e0d9783abf6d3c40566b9efbffe7e to your computer and use it in GitHub Desktop.
Save retran/c92e0d9783abf6d3c40566b9efbffe7e to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
public class HashTable
{
private final int numberOfBuckets = 50;
private final Vector<List<HashTableNode>> buckets;
private class HashTableNode
{
private String key;
private String value;
public HashTableNode(String key, String value)
{
this.key = key;
this.value = value;
}
public String getKey()
{
return key;
}
public String getValue()
{
return value;
}
}
public HashTable()
{
buckets = new Vector<>();
buckets.ensureCapacity(50);
}
public void add(String key, String value)
{
int hash = hash(key);
List<HashTableNode> bucket = buckets.elementAt(hash);
if (bucket == null)
{
bucket = new ArrayList<>();
buckets.add(hash, bucket);
}
bucket.add(new HashTableNode(key, value));
}
public String get(String key)
{
int hash = hash(key);
List<HashTableNode> bucket = buckets.elementAt(hash);
if (bucket == null)
{
return null;
}
for (HashTableNode node : bucket)
{
if (node.getKey().equals(key))
{
return node.getValue();
}
}
return null;
}
private int hash(String value)
{
return value.charAt(0) % numberOfBuckets;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment