Write a Map yourself

Learning Java video on iku learning online, there is a function of implementing map by yourself, here is how to achieve it
package com.jbx.hash;
/**
 * The reason why the function of custom implementation of Map is not perfect is that the for loop affects the efficiency
 * @author Administrator
 *Map: store key-value pairs, find the corresponding value object according to the key object, the key cannot be repeated
 */
public class SxtMap001 {
	
	SxtEntry[] arr = new SxtEntry[990];
	int size;
	public void put(Object key,Object value){
		SxtEntry e = new SxtEntry(key,value);
		// Solve the problem of unique key value
		for (int i=0;i<size; i++){
			if(arr[i].key.equals(key)){
				arr[i].value = value;
				return ;
			}
			
		}
		arr[size++] = e;
	}
	public Object get(Object key){
		for (int i = 0; i < size; i++) {
			if(arr[i].key.equals(key)){
				return arr[i].value;
			}
		}
		return null;
	}
	public boolean containsKey(Object key){
		for(int i =0;i<size;i++){
			if(arr[i].key.equals(key)){
				return true;
			}
		}
		return false;
	}
	public boolean containsValue(Object value){
		for(int i =0;i<size;i++){
			if(arr[i].value.equals(value)){
				return true;
			}
		}
		return false;
	}
	public static void main(String[] args) {
		SxtMap001 m = new SxtMap001();
		m.put("1", "你好");
		m.put("2", "拜拜");
		m.put("2", "拜拜拜");
		System.out.println(m.get("2"));//拜拜拜
		System.out.println(m.containsKey("1"));//true
		System.out.println(m.containsValue("拜拜"));//false
		System.out.println(m.containsValue("拜拜"));//false
		System.out.println(m.get("2"));//拜拜拜
	}
	
}

class SxtEntry{
	Object key;
	Object value;
	public SxtEntry(Object key, Object value) {
		super();
		this.key = key;
		this.value = value;
	}
	
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326643176&siteId=291194637