skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Sunday, September 16, 2012

Convert generic Array object to String

Posted by Admin at 12:46 AM – 0 comments
 

Now easily get the contents of any Java Array object, formatted as a String using one simple method, instead of repeatedly writing code to iterate the Arrays and process each item individually.


public static String arrayToString(Object array) {
 if (array == null) {
  return "[NULL]";
 } else {
  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();
 }
}

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger