Skip to content

Instantly share code, notes, and snippets.

@zer0tonin
Created April 10, 2018 20:51
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 zer0tonin/0abebec227f826c9be6630cf34a7c917 to your computer and use it in GitHub Desktop.
Save zer0tonin/0abebec227f826c9be6630cf34a7c917 to your computer and use it in GitHub Desktop.
import java.util.LinkedList;
import java.lang.Object;
public class HashTable {
private final int size = 100;
private final LinkedList<Object>[] keyValues;
public HashTable() {
keyValues = new LinkedList[size];
}
public void add(String key, Object value) {
Integer hash = hash(key);
LinkedList<Object> list = keyValues[hash % 100];
if (list == null) {
list = new LinkedList<>();
}
list.add(key);
list.add(value);
keyValues[hash % 100] = list;
}
public Object get(String key) {
Integer hash = hash(key);
LinkedList<Object> list = keyValues[hash % 100];
int index =list.indexOf(key);
return list.get(index+1);
}
private Integer hash(String key) {
return Integer.valueOf(key.chars().sum());
}
}
import org.junit.Test;
import junit.framework.Assert;
public class HashTableTest {
@Test
public void testAddGetSimple() {
HashTable hashTable = new HashTable();
hashTable.add("key", 123L);
hashTable.add("key2", "ok");
Assert.assertEquals(123L, hashTable.get("key"));
Assert.assertEquals("ok", hashTable.get("key2"));
}
public void testAddGetCollision() {
HashTable hashTable = new HashTable();
hashTable.add("abc", 123L);
hashTable.add("cba", "ok");
Assert.assertEquals(123L, hashTable.get("abc"));
Assert.assertEquals("ok", hashTable.get("cba"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment