HTMap.java 1019 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. public class HTMap<K,V>{
  2. private class Entry<K,V> {
  3. K key;
  4. V value;
  5. @Override
  6. public int hashCode(){
  7. return key.hashCode();
  8. }
  9. }
  10. private Entry<K,V>[] table;
  11. private int size;
  12. public HTMap(int size){
  13. this.size = size;
  14. table = (Entry<K,V>[]) new HTMap.Entry[size];
  15. }
  16. public V put(K key, V value){
  17. int i = Math.abs(key.hashCode() % table.length);
  18. V old = null;
  19. while (table[i] != null && !table[i].key.equals(key)) {
  20. i = (i + 1) % table.length;
  21. }
  22. if(table[i].key == key){
  23. old = table[i].value;
  24. }
  25. table[i].key = key;
  26. table[i].value = value;
  27. return old;
  28. }
  29. public V get(K key){
  30. int i = Math.abs(key.hashCode() % table.length);
  31. while (table[i] != null && !table[i].key.equals(key)) {
  32. i = (i + 1) % table.length;
  33. }
  34. return table[i] != null ? table[i].value : null;
  35. }
  36. }