Created
April 10, 2018 20:51
-
-
Save zer0tonin/0abebec227f826c9be6630cf34a7c917 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.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()); | |
} | |
} |
This file contains hidden or 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 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