Map implementation is actually very simple, a key for a value on the line.

This Map is written to play, is to tell beginners that we can also write a simple Map to use

Code:

public class MyMap<K.V> {
    private Node<K, V>[] nodes;
    private int size;

    private static class Node<K.V> {
        K key;
        V value;

        Node(K key, V value) {
            this.key = key;
            this.value = value; }}private void put(K key, V value) {
        if (nodes == null) {
            nodes = new Node[10];
        }
        int index = indexOfKey(key);
        if(index ! = -1) {
            nodes[index].value = value;
        } else {
            nodes[size] = newNode<>(key, value); size++; }}private int indexOfKey(K key) {
        for (int index = 0; index < size; index++) {
            if (key.equals(this.nodes[index].key)) {
                returnindex; }}return -1;
    }

    public V get(K key) {
        int index = indexOfKey(key);
        if(index ! = -1) {
            return (V) nodes[index].value;
        }
        return null;
    }

    public int size(a) {
        return size;
    }

    public void remove(K key) {
        int index = indexOfKey(key);

        if(index ! = -1) {
            System.arraycopy(nodes, index + 1, nodes, index, size - 1);
            nodes[--size] = null; }}public void clear(a) {
        nodes = null;
        size = 0;
    }

    private static class Person {
        private String name;
        private Integer age;

        public Person(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        public String getName(a) {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge(a) {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public String toString(a) {
            return "Person{" +
                    "name='" + name + '\' ' +
                    ", age=" + age +
                    '} '; }}public static void main(String[] args) {
        MyMap<String, Person> myMap = new MyMap<>();
        myMap.put("lzl".new Person("lzl".21));
        myMap.put("zwt".new Person("zwt".21));
        System.out.println("LZL's age is:" + myMap.get("lzl").getAge());
        System.out.println("The age of ZWT is:" + myMap.get("zwt").getAge());
        System.out.println("MyMap size is:" + myMap.size());

        myMap.clear();
        System.out.println("Clear myMap size is:" + myMap.size());

        MyMap<String, Integer> myMap1 = new MyMap<>();
        myMap1.put("zwt".21);
        System.out.println(myMap1.get("zwt")); }}Copy the code

Results:

LZL's age is:21The age of ZWT is:21The size of myMap is:2The size of clear myMap is:0
21
Copy the code

The Map interface is not implemented and the underlying array expansion is not taken into account.