Loading

递归计数

package t20220518;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: DengJia
 * @Date: 2022/5/21 0:17
 * @Description:
 */

public class TypeCounter extends HashMap<Class<?>, Integer> {

    private Class<?> baseType;

    public TypeCounter(Class<?> baseType) {
        this.baseType = baseType;
    }

    public void count(Object obj) {
        Class<?> type = obj.getClass();
        if (!baseType.isAssignableFrom(type)) {
            throw new RuntimeException(obj + " incorrect type: " + type + ", should be type or subtype of " + baseType);
        }
        countClass(type);
    }

    private void countClass(Class<?> type) {
        Integer quantity = get(type);
        put(type, quantity == null ? 1 : quantity + 1);
        Class<?> superclass = type.getSuperclass();
        if (superclass != null && baseType.isAssignableFrom(superclass)) {
            countClass(superclass);
        }
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder("{");
        for (Map.Entry<Class<?>, Integer> pair : entrySet()) {
            result.append(pair.getKey().getSimpleName());
            result.append("=");
            result.append(pair.getValue());
            result.append(", ");
        }
        result.delete(result.length() - 2, result.length());
        result.append("}");
        return result.toString();
    }

    public static void main(String[] args) {
        TypeCounter typeCounter = new TypeCounter(Object.class);

        Integer i = 10;
        Double j = 1.1;
        Byte k = 7;
        typeCounter.count(i);
        typeCounter.count(j);
        typeCounter.count(k);

        System.out.println(typeCounter);
    }
}

posted @ 2022-05-21 00:46  溫柔の風  阅读(38)  评论(0编辑  收藏  举报