自己写一个Map
Map的实现其实很简单,一个key对应一个value就行 。
本Map是写着玩的,是想告诉初学者我们也可以写一个简单的Map来自己用
代码:
public class MyMap<K, V> {
private Node<K, V>[] nodes;
private int size;
private static class Node<K, V> {
K key;
V value;
Node(K key, V value) {
this.key = key;
this.value = value;
}
}
private void put(K key, V value) {
if (nodes == null) {
nodes = new Node[10];
}
int index = indexOfKey(key);
if (index != -1) {
nodes[index].value = value;
} else {
nodes[size] = new Node<>(key, value);
size++;
}
}
private int indexOfKey(K key) {
for (int index = 0; index < size; index++) {
if (key.equals(this.nodes[index].key)) {
return index;
}
}
return -1;
}
public V get(K key) {
int index = indexOfKey(key);
if (index != -1) {
return (V) nodes[index].value;
}
return null;
}
public int size() {
return size;
}
public void remove(K key) {
int index = indexOfKey(key);
if (index != -1) {
System.arraycopy(nodes, index + 1, nodes, index, size - 1);
nodes[--size] = null;
}
}
public void clear() {
nodes = null;
size = 0;
}
private static class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public static void main(String[] args) {
MyMap<String, Person> myMap = new MyMap<>();
myMap.put("lzl", new Person("lzl", 21));
myMap.put("zwt", new Person("zwt", 21));
System.out.println("lzl的年龄是:" + myMap.get("lzl").getAge());
System.out.println("zwt的年龄是:" + myMap.get("zwt").getAge());
System.out.println("myMap的大小是:" + myMap.size());
myMap.clear();
System.out.println("clear myMap的大小是:" + myMap.size());
MyMap<String, Integer> myMap1 = new MyMap<>();
myMap1.put("zwt", 21);
System.out.println(myMap1.get("zwt"));
}
}
结果:
lzl的年龄是:21
zwt的年龄是:21
myMap的大小是:2
clear myMap的大小是:0
21
并没有实现Map接口 , 没有考虑到底层数组的扩容 。