Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

shorter way to print the contents of an array?

Status
Not open for further replies.

carpeliam

Programmer
Mar 17, 2000
990
US
I have an object that needs printing, but I get it cast as "Object". The following is the only way I know how to return a String representation of this:
Code:
    private String getValueAsArrayString() {
        assert value.getClass().isArray();
        if (value instanceof boolean[])
            return Arrays.toString((boolean[]) value);
        else if (value instanceof byte[])
            return Arrays.toString((byte[]) value);
        else if (value instanceof char[])
            return Arrays.toString((char[]) value);
        else if (value instanceof double[])
            return Arrays.toString((double[]) value);
        else if (value instanceof float[])
            return Arrays.toString((float[]) value);
        else if (value instanceof int[])
            return Arrays.toString((int[]) value);
        else if (value instanceof long[])
            return Arrays.toString((long[]) value);
        else if (value instanceof short[])
            return Arrays.toString((short[]) value);
        else if (value instanceof Object[])
            return Arrays.deepToString((Object[]) value);
        else
            throw new AssertionError("unknown type: " + value.getClass());
    }
is there a better way? did I forget anything?

Liam Morley
lmorley@wpi.edu
"light the deep, and bring silence to the world.
light the world, and bring depth to the silence."
 
I just noticed that Arrays.toString() only works in jdk1.5. Which means, to do this in 1.4, I'd have to still do an instanceof, as well as a cast, and then iterate through the array- there HAS to be a better way. <p>Liam Morley<br><A HREF="mailto:"></A><br>&quot;light the deep, and bring silence to the world.<br>light the world, and bring depth to the silence.&quot;
 
solved.<BR><BR><DIV id="code"><h4>CODE</h4><div class="body">import java.lang.reflect.Array;<BR>for (int i = 0; i &lt; Array.getLength(value); i++)<BR>&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(Array.get(value, i));</DIV></DIV> <p>Liam Morley<br><A HREF="mailto:"></A><br>&quot;light the deep, and bring silence to the world.<br>light the world, and bring depth to the silence.&quot;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top