Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package cs2321;
- import net.datastructures.Entry;
- import net.datastructures.Map;
- /*
- * @author Timothy Laynes
- * CS2321
- */
- public class HashMap<K, V, E> extends AbstractMap<K, V> implements Map<K, V> {
- /*
- * Use Array of UnorderedMap<K,V> for the Underlying storage for the map of
- * entries.
- *
- */
- private UnorderedMap<K, V>[] table;
- int size; // number of mappings(entries)
- int capacity; // The size of the hash table.
- /**
- * Constructor that takes a hash size
- *
- * @param hashtable size: the number of buckets to initialize
- */
- public HashMap(int hashtablesize) {
- capacity = hashtablesize;
- table = (UnorderedMap<K, V>[]) new UnorderedMap[capacity];
- }
- /**
- * Constructor that takes no argument Initialize the hash table with default
- * hash table size: 17
- */
- public HashMap() {
- this(17);
- }
- /*
- * This method should be called by map an integer to the index range of the hash
- * table
- */
- private int hashValue(K key) {
- return Math.abs(key.hashCode()) % capacity;
- }
- /*
- * The purpose of this method is for testing if the table was doubled when
- * rehashing is needed. Return the the size of the hash table. It should be 17
- * initially, after the load factor is more than 0.75, it should be doubled.
- */
- @Override
- public int size() {// returns the size of the Hash map
- return size;
- }
- @Override
- public boolean isEmpty() {// returns a boolean indicating if its empty
- // TODO Auto-generated method stub
- return size() == 0;
- }
- @TimeComplexity("0(1)")
- @Override
- /*
- *
- */
- public V get(K key) {
- UnorderedMap<K, V> map = table[hashValue(key)];
- if (map == null)
- return null;
- return map.get(key);
- }
- @TimeComplexity("0(1)")
- @Override
- public V put(K key, V value) {
- UnorderedMap<K, V> map = table[hashValue(key)];
- V answer = null;
- if (map == null) {
- map = table[hashValue(key)] = new UnorderedMap<>();
- int oldSize = map.size();
- answer = map.put(key, value);
- size += (map.size() - oldSize);
- }
- return answer;
- }
- @TimeComplexity("0(1)")
- @Override
- public V remove(K key) {
- UnorderedMap<K, V> map = table[hashValue(key)];
- if (map == null) {
- return null;
- }
- int oldSize = map.size();
- V answer = map.remove(key);
- size -= (oldSize - map.size());
- return answer;
- }
- @Override
- public Iterable<Entry<K, V>> entrySet() {
- ArrayList<Entry<K, V>> buffer = new ArrayList<>();
- for (int h = 0; h < capacity; h++) {
- if (table[h] != null) {
- for (Entry<K, V> entry : table[h].entrySet()) {
- buffer.addLast(entry);
- }
- }
- }
- return buffer;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement