Created
April 17, 2017 11:06
-
-
Save retran/c92e0d9783abf6d3c40566b9efbffe7e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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