Click here to Skip to main content
13,247,891 members (41,825 online)
Click here to Skip to main content
Add your own
alternative version


7 bookmarked
Posted 7 Apr 2004

Java Generic Code - Convert Array Contents to a String in a Generic Way

, 7 Apr 2004
Rate this:
Please Sign up or sign in to vote.
Presenting a generic way to convert Array contents to Strings


In this article, I hope to start a series of articles discussing Java Generic Code. I will start with a problem that although easily solved, reared up its ugly head in many code sessions with my peers. ;)

Java Generic Code - Convert Array Contents to a String in a Generic Way

Imagine that you have the following code:

public static void main(String[] args) {
  Object[] arrayList = {
    new int[] {0, 1, 2 ,3},
    new double[] {0.1d, 1.0d, 3.2d ,3.5d},
    new java.awt.Color[] {java.awt.Color.BLACK, java.awt.Color.WHITE},
    new boolean[] {true, false, true, true, false, false}
  for (int i = 0; i < arrayList.length; i++) {
    System.out.println("Array[" + (i + 1) + "] = " + arrayToString(arrayList[i]));

And somehow (due to the "miracle" of the arrayToString() method) the output looks like this:

Array[1] = [0, 1, 2, 3] 
Array[2] = [0.1, 1.0, 3.2, 3.5] 
Array[3] = [java.awt.Color[r=0,g=0,b=0], java.awt.Color[r=255,g=255,b=255]] 
Array[4] = [true, false, true, true, false, false] 

You'd be happy with such a method because it means you can 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.

Why This is Actually Important

This may sound like a trivial problem, but let me emphasize that a lot of programmers working in teams will attempt to write their own code to solve this. Having many components carry out the same functionality is a waste, and be warned that while some programmers will get it right and won't have any bugs in solving this problem, other programmers may accidentally write a method to display an Array's contents suffering from bugs! I actually wasted 20 minutes, together with another programmer, because his debug code did not display the LAST item in an Array object, causing us to think the last item actually was never sent properly.


On With the Show

Such a method does not exist in the JDK but it is very short and easy to understand; examine the following code:

 1  public static String arrayToString(Object array) {
 2    if (array == null) {
 3      return "[NULL]";
 4    } else {
 5      Object obj = null;
 6      if (array instanceof Hashtable) {
 7        array = ((Hashtable)array).entrySet().toArray();
 8      } else if (array instanceof HashSet) {
 9        array = ((HashSet)array).toArray();
10      } else if (array instanceof Collection) {
11        array = ((Collection)array).toArray();
12      }
13      int length = Array.getLength(array);
14      int lastItem = length - 1;
15      StringBuffer sb = new StringBuffer("[");
16      for (int i = 0; i < length; i++) {
17        obj = Array.get(array, i);
18        if (obj != null) {
19          sb.append(obj);
20        } else {
21          sb.append("[NULL]");
22        }
23        if (i < lastItem) {
24          sb.append(", ");
25        }
26      }
27      sb.append("]");
28      return sb.toString();
29    }
30  }

Let's examine the code in detail.

Lines 2-4

First off, we check if the array passed to us is null, if so, lines 2-3 will return "[NULL]" and we're done!

Lines 5-12

If the array is not null, then lines 6-12 make sure that if - by mistake? - we were handed a Hashtable/HashSet/Collection object, it will be properly converted to an array object for us!

Line 13

Here we use Java's Array class to generically retrieve the length of the array in question; this of course is needed because if you remember, we receive the array as an Object and not as a proper Array of any Java native type.

Lines 14-16

Calculate the index of the last item; create a StringBuffer to collect the text output; initiate a for-loop to go through all the items in the array.

Line 17

Here again, we use Java's Array class to generically retrieve the currently indexed item.

Line 18-26

Given the currently indexed item in the array, we either add the item's contents - as expressed by its toString() method - and add it to the StringBuffer, or if the current item is null, we add "[NULL]" to the StringBuffer to show there is nothing in this slot. At line 23, we check if the item was the last one, if it is not, line 24 will add a comma and a space so we can continue to build the text output properly.

Line 27-30

Now, we append a "]" character to the end of the StringBuffer, and return the whole text out of the StringBuffer back to our calling method.

I hope this little method will help, I know I have found it very helpful when I had to debug code that had a lot of different types of Array objects which were all to be printed, formatted into Java Exceptions and other interesting things which required the contents of the Array to be easily converted into a text String.



  • 7th April, 2004: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Doron Barak
Web Developer
Canada Canada
No Biography provided

You may also be interested in...

Comments and Discussions

Question?? Pin
GreatGhoul13-Jan-10 19:41
memberGreatGhoul13-Jan-10 19:41 
GeneralNested Arrays Pin
Davy Boy12-Dec-05 6:35
memberDavy Boy12-Dec-05 6:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171114.1 | Last Updated 8 Apr 2004
Article Copyright 2004 by Doron Barak
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid