solved Task 4

This commit is contained in:
schrom01 2022-11-15 20:20:46 +01:00
parent d2d55109a8
commit 7b9195bb46
1 changed files with 16 additions and 5 deletions

View File

@ -6,6 +6,7 @@ import java.util.*;
public class MyHashtable<K, V> implements Map<K, V> { public class MyHashtable<K, V> implements Map<K, V> {
private K[] keys;// = (K[]) new Object[10]; private K[] keys;// = (K[]) new Object[10];
private V[] values;// = (V[]) new Object[10]; private V[] values;// = (V[]) new Object[10];
int initialSize;
private int hash(Object k) { private int hash(Object k) {
int h = Math.abs(k.hashCode()); int h = Math.abs(k.hashCode());
@ -14,8 +15,8 @@ public class MyHashtable<K, V> implements Map<K, V> {
public MyHashtable(int size) { public MyHashtable(int size) {
// to be done // to be done
keys = (K[]) new Object[size]; initialSize = size;
values = (V[]) new Object[size]; clear();
} }
public MyHashtable() { public MyHashtable() {
@ -25,15 +26,25 @@ public class MyHashtable<K, V> implements Map<K, V> {
// Removes all mappings from this map (optional operation). // Removes all mappings from this map (optional operation).
public void clear() { public void clear() {
// to be done // to be done
keys = (K[]) new Object[1000]; keys = (K[]) new Object[initialSize];
values = (V[]) new Object[1000]; values = (V[]) new Object[initialSize];
}
private void extendTable() {
K[] actualKeys = keys;
V[] actualValues = values;
keys = (K[]) new Object[actualKeys.length * 2];
values = (V[]) new Object[actualKeys.length * 2];
for(int i = 0; i < actualKeys.length; i++) {
put(actualKeys[i], actualValues[i]);
}
} }
// Associates the specified value with the specified key in this map (optional operation). // Associates the specified value with the specified key in this map (optional operation).
public V put(K key, V value) { public V put(K key, V value) {
// to be done // to be done
if(size() >= keys.length) { if(size() >= keys.length) {
throw new IllegalStateException("Overflow"); extendTable();
} else { } else {
int i = -1; int i = -1;
int hashCode = hash(key); int hashCode = hash(key);