package com.shrimpking.t15;

import com.sun.xml.internal.bind.v2.model.core.MaybeElement;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2024/9/10 20:43
 */
public class MyMap<K,V>
{
    private class Pair<K,V>{
        public K key;
        public V value;

        public Pair(K key,V value){
            this.key = key;
            this.value = value;
        }
    }

    private List<Pair<K,V>> elements;
    private int size;

    public MyMap(int length){
        elements = new ArrayList<>(length);
        size = 0;
    }

    public int size(){
        return this.size;
    }

    public void put(K key,V value){
        for (int i = 0; i < this.size -1; i++){
            if(elements.get(i).key.equals(key)){
                elements.get(i).value = value;
                return;
            }
        }
        elements.add(new Pair<>(key,value));
        this.size = elements.size();
    }

    public V get(K key){
        for (int i = 0; i < size; i++){
            if(elements.get(i).key.equals(key)){
                return elements.get(i).value;
            }
        }
        return null;
    }

    @Override
    public String toString()
    {
        StringBuilder strb = new StringBuilder();
        strb.append("[");
        for (int i = 0; i < this.size -1; i++){
            Pair<K,V> p = elements.get(i);
            strb.append(p.key);
            strb.append(":");
            strb.append(p.value);
            strb.append(",");
        }
        //最后一个元素
        Pair<K,V> p = elements.get(size - 1);
        if(p != null){
            strb.append(p.key);
            strb.append(":");
            strb.append(p.value);
        }
        strb.append("]");
        return strb.toString();
    }

    public static void main(String[] args)
    {
        MyMap<Integer,String> map = new MyMap<>(10);
        map.put(1,"one");
        map.put(2,"two");
        map.put(3,"three");
        map.put(4,"four");
        System.out.println(map);
        map.put(5,"five");
        System.out.println(map);
        System.out.println("size=" + map.size);
        System.out.println("3映射的值是:" + map.get(3));
        System.out.println("6映射的值是:" + map.get(6));


    }
}