I have a map which is defined like
HashMap<Object, Object> hashMap;
Now I need to iterate over each pair and print the key and value. Doing key.toString() and value.toString() works well for types like ArrayList. But toString() on an array won't give a readable string.
I am aware about Arrays.toString(). But I can't use it in my case because Arrays.toString() expects an object array and all I have is an object. So I wrote a custom code which looks like,
private String convertToHumanReadableFormat(Object value) {
if (value == null) return "N/A";
if (value.getClass().isArray()) {
return convertArrayToReadableFormat(value);
}
return value.toString();
}
private String convertArrayToReadableFormat(Object value) {
String output = "[";
int arrayLength = Array.getLength(value);
for (int i = 0; i < arrayLength; i++) {
Object element = Array.get(value, i);
if (element != null) {
if (element.getClass().isArray()) {
output += convertArrayToReadableFormat(element);
}
else {
output += element.toString();
}
}
if ((i + 1) < arrayLength)
output += ", ";
}
output += "]";
return output;
}
I am actually duplicating what Arrays.deepToString() does. But I can't see a way to just use Arrays.toString() or Arrays.deepToString().
Is this the correct approach to the problem or is there any way to get those standard methods working for me?
Any help would be great.