Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- interface Map<K, V> {
- void put(K key, V value);
- V get(K key);
- boolean containsKey(K key);
- interface Entry<K, V> {
- K getKey();
- V getValue();
- Entry<K, V> getNext();
- }
- }
- class HashMap<K, V> implements Map<K, V> {
- private final static int DEFAULT_CAPACITY = 16;
- private Node<K, V>[] nodes;
- @SuppressWarnings("unchecked")
- public HashMap() {
- nodes = (Node<K, V>[]) new Node[DEFAULT_CAPACITY];
- }
- @Override
- public void put(K key, V value) {
- int position = hash(key);
- Node<K, V> node = nodes[position];
- if (node == null) {
- nodes[position] = new Node<>(key, value, null);
- } else {
- while (node.getNext() != null) {
- node = node.getNext();
- }
- node.next = new Node<>(key, value, null);
- }
- }
- @Override
- public V get(K key) {
- int position = hash(key);
- Node<K, V> node = nodes[position];
- if (node == null) {
- return null;
- }
- while (!node.getKey().equals(key)) {
- node = node.getNext();
- if (node == null) {
- return null;
- }
- }
- return node.getValue();
- }
- @Override
- public boolean containsKey(K key) {
- int position = hash(key);
- Node<K, V> node = nodes[position];
- if (node == null) {
- return false;
- }
- while (!node.getKey().equals(key)) {
- node = node.getNext();
- if (node == null) {
- return false;
- }
- }
- return true;
- }
- private int hash(K key) {
- return key == null ? 0 : key.hashCode() % nodes.length;
- }
- private static class Node<K, V> implements Map.Entry<K, V> {
- private final K key;
- private V value;
- private Node<K, V> next;
- public Node(K key, V value, Node<K, V> next) {
- this.key = key;
- this.value = value;
- }
- @Override
- public K getKey() {
- return key;
- }
- @Override
- public V getValue() {
- return value;
- }
- @Override
- public Node<K, V> getNext() {
- return next;
- }
- }
- }
- public class Application {
- public static void main(String[] args) {
- Map<String, Integer> numbersByString = new HashMap<>();
- numbersByString.put("1", 1);
- numbersByString.put("2", 2);
- numbersByString.put("3", 3);
- System.out.println(numbersByString.get("1").equals(1));
- System.out.println(numbersByString.get("2").equals(2));
- System.out.println(numbersByString.get("3").equals(3));
- System.out.println(numbersByString.get("4") == null);
- System.out.println(numbersByString.containsKey("1") == true);
- System.out.println(numbersByString.containsKey("2") == true);
- System.out.println(numbersByString.containsKey("3") == true);
- System.out.println(numbersByString.containsKey("4") == false);
- }
- }
Add Comment
Please, Sign In to add comment