fork download
  1. import java.util.*;
  2.  
  3. interface IDictionary<K, V> {
  4. void insert(K key, V value);
  5. V get(K key);
  6. int size();
  7. boolean isEmpty();
  8. }
  9.  
  10. class Entry<K, V> {
  11. K key;
  12. V value;
  13. public Entry(K key, V value) {
  14. this.key = key;
  15. this.value = value;
  16. }
  17.  
  18. @Override
  19. public String toString() {
  20. return key.toString() + "#" + value.toString();
  21. }
  22. }
  23.  
  24. class Dictionary<K, V> implements IDictionary<K, V> {
  25. private int size = 0;
  26. private int tableSize = 10;
  27. private Object table[];
  28. public Dictionary() {
  29. table = new Object[tableSize];
  30. }
  31.  
  32. public void insert(K key, V value) {
  33. int hash = key.hashCode();
  34. hash = (hash & 0x7fffffff) % tableSize;
  35. if(table[hash] != null) {
  36. System.out.println("udpate 😂");
  37. table[hash] = new Entry(key, value);
  38. } else {
  39. System.out.println("Inserted 😁");
  40. table[hash] = new Entry(key, value);
  41. size += 1;
  42. }
  43. // System.out.println(hash);
  44.  
  45. }
  46.  
  47. public V get(K key) {
  48. int hash = key.hashCode();
  49. hash = (hash & 0x7fffffff) % tableSize;
  50. Entry e = (Entry)table[hash];
  51. if(e == null) {
  52. return null;
  53. }
  54. return (V)e.value;
  55. }
  56.  
  57. @Override
  58. public int size() {
  59. return size;
  60. }
  61.  
  62. public boolean isEmpty() {
  63. return size == 0;
  64. }
  65. }
  66.  
  67. class Main {
  68. public static void main(String[] args) {
  69. Dictionary<String, String> dictionary = new Dictionary<>();
  70. dictionary.insert("AMITH", "K");
  71. dictionary.insert("AMITH", "K");
  72. System.out.println(dictionary.size());
  73. dictionary.insert("LUFFY", "K");
  74. System.out.println(dictionary.size());
  75. System.out.println(dictionary.get("LUFFY"));
  76. dictionary.insert("LUFFY", "AMITH");
  77. System.out.println(dictionary.size());
  78. System.out.println(dictionary.get("LUFFY"));
  79. }
  80. }
Success #stdin #stdout 0.07s 54780KB
stdin
Standard input is empty
stdout
Inserted 😁
udpate 😂
1
Inserted 😁
2
K
udpate 😂
2
AMITH