Map的工作原理

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));


    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虾米大王

有你的支持,我会更有动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值