Generic Array To String Function

Submitted by:Jhon Jhon

Date added:02 February, 2013

Category:Java

Example code for Generic Array To String Function

Tags: array to string

Code Snippet:

public static String arrayToString(Object array) {
if (array == null) { return "[NULL]"; }
Object obj = null;
if (array instanceof Hashtable) { array = ((Hashtable)array).entrySet().toArray(); }
else if (array instanceof HashSet) { array = ((HashSet)array).toArray(); }
else if (array instanceof Collection) { array = ((Collection)array).toArray(); }

int length = Array.getLength(array);
int lastItem = length - 1;
StringBuffer sb = new StringBuffer("[");
for (int i = 0; i < length; i++) {
obj = Array.get(array, i);
if (obj != null) { sb.append(obj); } else { sb.append("[NULL]"); }
if (i < lastItem) { sb.append(", "); }
}
sb.append("]");
return sb.toString();
}
}
 
 

Comments