参数是需要统计的顶级类,及类的集合
通过键值对map来统计数据
逐个取出累计类别出现次数
继承HashMap,使用泛型
类名TypeCounter
个人实现:
package thinking;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.management.RuntimeErrorException;
public class TypeCounter extends HashMap<Class<?>, Integer> {
Class<?> baseType;
public TypeCounter(Class baseType){
this.baseType = baseType;
}
void count(Object obj){
Class<?> objClass= obj.getClass();
if(!baseType.isAssignableFrom(objClass)){
throw new RuntimeException("未有此子类");
}
countClass(objClass);
}
void countClass(Class<?> t){
put(t, get(t)==null?1:get(t)+1);
Class<?> superClass= t.getSuperclass();
if(baseType.isAssignableFrom(superClass) && superClass!=null){
countClass(superClass);
}
}
public String toString(){
String result = null;
for(Class<?> key:this.keySet()){
result = key.getSimpleName()+":"+this.get(key);
}
return result;
}
public static void main(String[] args){
List<Integer> list = new ArrayList<Integer>();
list.add(12);
list.add(24);
TypeCounter typeCounter = new TypeCounter(ArrayList.class);
typeCounter.count(list);
System.out.println(typeCounter);
}
}
原书实现:
package thinking;
import java.util.HashMap;
import java.util.Map;
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+" incorect type: "+type+",should be type or be subtype of "+ baseType);
}
countClass(type);
}
private void countClass(Class<?> type) {
Integer quantity = get(type);
put(type, quantity==null?1:quantity+1);
Class<?> supClass = type.getSuperclass();
if(supClass!=null && baseType.isAssignableFrom(supClass)){
countClass(supClass);
}
}
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();
}
}