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));
}
}
Map的工作原理
原创
©著作权归作者所有:来自51CTO博客作者虾米大王的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:Map的性能测试
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章