Java 如何从HashMap获取值对象大小?

Java 如何从HashMap获取值对象大小?,java,object,hashmap,Java,Object,Hashmap,我有一张物体的地图: HashMap<Object, Object> map = new HashMap<>(); map.put(1, new String("Hello")); map.put("two", 12345); map.put(3, new byte[]{12,20,54}); HashMap map=newhashmap(); map.put(1,新字符串(“Hello”); 地图.put("2",12345);; put(3,新字节[]{12,20

我有一张物体的地图:

HashMap<Object, Object> map = new HashMap<>();

map.put(1, new String("Hello"));
map.put("two", 12345);
map.put(3, new byte[]{12,20,54});
HashMap map=newhashmap();
map.put(1,新字符串(“Hello”);
地图.put("2",12345);;
put(3,新字节[]{12,20,54});
如何打印每个值对象的大小


请帮忙

根据您给定的设计,您有一个非常糟糕的选项,即检查对象的当前类型并定义一个逻辑以了解其
大小:

public int size(Object o) {
    if (o instanceof String) {
        return ((String)o.)length();
    }
    if (o instanceof Object[].class) {
        return ((Object[])o).length;
    }
    if (o instanceof byte[].class) {
        return ((byte[])o).length;
    }
    //and on and on...
    //if something isn't defined, just return 0 or another default value
    return 0;
}

但请注意,这是一种糟糕的方法,因为您的设计很糟糕。如果你能解释你真正的问题就更好了。更多信息:

你可能想回到过去,重新思考你的设计,因为一般来说,按你现在的方式混合输入是个坏主意

也就是说,如果这不是您的选项,您需要检查对象的类型,然后为每个定义的对象打印“大小”:

public void printSize(Object o) {
    if (o instanceof String) {
        String s = (String) o;
        System.out.println(s.length());
    } else if (o instanceof byte[]) {
        byte[] b = (byte[]) o;
        System.out.println(b.length);
    } else if (o instanceof Integer) {
        Integer i = (Integer) o;
        System.out.println(String.valueOf(i).length());
    // and so on for other types
    } else {
        throw new InputMismatchException("Unknown type");
    }
}

你如何定义尺寸?内存使用情况?你可能想看看这个use java.lang.instrumentation包,看看这个链接@user2282950 int的长度是多少?说真的,你必须改变你当前的设计。你可以强制转换而不是分配新的变量。你可以,但我认为明确声明每种类型的变量会使代码对那些可怜的傻瓜来说更具可读性,他们必须在一年内维护这些变量,并试图弄清楚到底发生了什么。谢谢,在“抛出新的InputMismatchException(“未知类型”);”之前缺少一个“else”;“如果我就是那个傻瓜,然后,如果需要,我会重写整个应用程序。。。