1. hashmap和hashtable 区别
hashtable put() get()都上锁了synchronized
可以
可以
二、代码实战
ArrayList和LinkedList 2种方式来实现
1.先定义接口
public interface MayiktMap<K,V>{
/**
* 集合 大小
*/
int size();
V put(K key, V value);
V get(K key);
interface Entry<K,V> {
K getKey();
V getValue();
}
}
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class ArrayListHashMap<K,V> implements MayiktMap<K,V> {
private int size;
private List<Node> nodes = new ArrayList<Node>();
public int size() {
return 0;
}
public V put(K key, V value) {
Node node = getNode(key);
if(node!=null){
node.v = value;
return node.getValue();
}
Node newNode = new Node(key, value);
nodes.add(newNode);
size++;
return value;
}
public V get(K key) {
return getNode(key).getValue();
}
private Node getNode(K key){
for (Node node :nodes) {
if(key.equals(node.k)){
return node;
}
}
return null;
}
@Data
class Node implements Entry<K,V>{
private K k;
private V v;
public K getKey() {
return k;
}
public V getValue() {
return v;
}
public Node(K k, V v) {
this.k = k;
this.v = v;
}
}
}
import lombok.Data;
import java.util.LinkedList;
public class LinkedListHashMap<K,V> implements MayiktMap<K,V> {
private LinkedList<Node>[] objects = new LinkedList[100];
/**
* 相同的连标存放hashcode值相同 但是对象不同
* @return
*/
public int size() {
return 0;
}
public V put(K key, V value) {
int index= key.hashCode()%objects.length;
LinkedList<Node> nodes = objects[index];
if(nodes == null){
nodes = new LinkedList<Node>();
}
nodes.add(new Node(key, value));
objects[index] = nodes;
return value;
}
public V get(K key) {
int index= key.hashCode()%objects.length;
LinkedList<Node> nodes = objects[index];
for (Node node :nodes) {
if(key.equals(node.k)){
return node.v;
} }
return null;
}
@Data
class Node implements Entry<K,V>{
private K k;
private V v;
public K getKey() {
return null;
}
public V getValue() {
return null;
}
public Node(K k, V v) {
this.k = k;
this.v = v;
}
}
}
public class Test001 {
public static void main(String[] args) {
ArrayListHashMap arrayListHashMap = new ArrayListHashMap<String,String>();
arrayListHashMap.put("mayi","kt");
System.out.println(arrayListHashMap.get("mayi"));
LinkedListHashMap<Object, String> linkedListHashMap = new LinkedListHashMap<Object, String>();
linkedListHashMap.put("a","mayi");
linkedListHashMap.put(97,"mayi2");
System.out.println(linkedListHashMap.get("a"));
System.out.println(linkedListHashMap.get(97));
}
}