-3

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 !

Yakoub
  • 11
  • 9

2 Answers2

2

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");
    }
}
azurefrog
  • 10,785
  • 7
  • 42
  • 56
  • You can cast instead of assigning new variables. – keyser May 05 '14 at 15:37
  • You can, but I thought that declaring a variable of each type explicitly would make the code more readable for the poor sucker who has to maintain this in a year and is trying to figure out what's going on. – azurefrog May 05 '14 at 15:38
  • thanks, that just missing an "else" before "throw new InputMismatchException("Unknown type");" – Yakoub May 05 '14 at 15:53
  • If I were that *sucker*, then I would rewrite the entire application if needed... – Luiggi Mendoza May 05 '14 at 15:53
1

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?

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332