#Hashtable and hashmap. I am struggling with two methods I need to write for a finished class.
14 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @dense dragon! Please use
/closeor theClose Postbutton above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
* Associates the specified value with the specified key in this map. If the map
* previously contained a mapping for the key, the old value is replaced.
*/
public V put(K key, V value) {
if(table[index(key)].key == null) {
table[index(key)].key = key;
table[index(key)].value = value;
} else {
if(table[index(key)].key == key) {
table[index(key)].value = value;
} else {
table[index(key)].key = key;
table[index(key)].value = value;
}
}
return value;
}
/**
* Returns the value to which the specified key is mapped, or null if this map
* contains no mapping for the key.
*/
public V get(K key) {
if(findNode(index(key), key) == null) {
return null;
}
return findNode(index(key), key).value;
}```
This is what I have done so far. It is not looking clean at all I know but I will look into that when I get it to work
This is what I am getting
And this is the finished class that I am supposed to use and write the methods for
private int size;
private Node<K, V>[] table;
public SimpleHashMap(int capacity) {
table = (Node<K, V>[]) new Node[capacity];
}
public SimpleHashMap() {
this(16);
}
private int index(K key) {
// färdig att använda
}
private Node<k, V> findNode(int index, K key) {
// färdig att använda
}
// Övriga metoder i klassen put, get ...
private static class Node<K, V> {
private K key;
private V value;
private Node<k, V> next;
private Node(K key, V value) {
this.key = key;
this.value = value;
this.next = null;
}
}
}```
first guess is that table[index(key)] is null
if(table[index(key)].key == null) { // your index(key) method is empty (how is it even compiled?)
table[index(key)].key = key; // if object in table is null, how you want to set it's properties? properties of null?
table[index(key)].value = value; // same here
}
index() method should return the position of object in the array table. Start from solving this problem first
read this article, it will be very helpful for you to understand
Hash Table with Introduction, Asymptotic Analysis, Array, Pointer, Structure, Singly Linked List, Doubly Linked List, Graph, Tree, B Tree, B+ Tree, Avl Tree etc.
and dont call index() multiple times