문제

I have a map of objects :

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

map.put(1, new String("Hello"));
map.put("two", 12345);
map.put(3, new byte[]{12,20,54});

How can i print each value object size ??

Please help !

도움이 되었습니까?

해결책

You probably want to go back and re-think your design, since it's generally a bad idea to mix type the way you are.

That being said, if that isn't an option for you, you'll need to check the type your object, then print the 'size' for each defined how you thing is appropriate:

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");
    }
}

다른 팁

From your given design, you have a very awful option that is checking the current type of the object and define a logic to know its size:

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;
}

But note that this is a bad approach since you have a bad design. It would be better if you explain your real problem instead. More info: What is the XY problem?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top