private static class MyHashMap<K, V> extends HashMap<K, V> {
public MyHashMap(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
System.out.println("MyHashMap(" + initialCapacity + ", " + loadFactor + ") -> " + getInfo());
}
public MyHashMap(int initialCapacity) {
super(initialCapacity);
System.out.println("MyHashMap(" + initialCapacity + ") -> " + getInfo());
}
public MyHashMap() {
System.out.println("MyHashMap() -> " + getInfo());
}
public MyHashMap(Map<? extends K, ? extends V> map) {
super(map);
System.out.println("MyHashMap(" + map + ") -> " + getInfo());
}
@Override
public V put(K key, V value) {
V v = super.put(key, value);
System.out.println("put(" + key + ", " + value + ") -> " + getInfo());
return v;
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
super.putAll(map);
System.out.println("putAll(" + map + ") -> " + getInfo());
}
private String getInfo() {
Object table = getField("table");
int tableSize = 0;
if (null != table && table.getClass().isArray()) {
tableSize = ((Object[]) table).length;
}
return String.format("{table: %03d, size: %03d}", tableSize, size());
}
private Object getField(String name) {
try {
Field field = HashMap.class.getDeclaredField(name);
field.setAccessible(true);
return field.get(this);
} catch (Exception e) {
return null;
}
}
}
// 无参构造
public static void main(String[] args) {
MyHashMap<String, String> hashMap = new MyHashMap<String, String>();
for (char i = 'A'; i <= 'Z'; i ++) {
hashMap.put(new String(new char[] {i}), new String(new char[] {i}));
}
}
MyHashMap() -> {
table: 000, size: 000}
put(A, A) -> {
table: 016, size: 001}
put(B, B) -> {
table: 016, size: 002}
put(C, C) -> {
table: 016, size: 003}
put(D, D) -> {
table: 016, size: 004}
put(E, E) -> {
table: 016, size: 005}
put(F, F) -> {
table: 016, size: 006}
put(G, G) -> {
table: 016, size: 007}
put(H, H) -> {
table: 016, size: 008}
put(I, I) -> {
table: 016, size: 009}
put(J, J) -> {
table: 016, size: 010}
put(K, K) -> {
table: 016, size: 011}
put(L, L) -> {
table: 016, size: 012}
put(M, M) -> {
table: 032, size: 013}
put(N, N) -> {
table: 032, size: 014}
put(O, O) -> {
table: 032, size: 015}
put(P, P) -> {
table: 032, size: 016}
put(Q, Q) -> {
table: 032, size: 017}
put(R, R) -> {
table: 032, size: 018}
put(S, S) -> {
table: 032, size: 019}
put(T, T) ->