Re: Customize toString() for arrays...?
On Thu, 22 Jul 2010, Simone wrote:
I also noticed that the solution with Arrays.asList(vector) works only
if vector is an array of a wrapper class and not if it's an array of a
primitive type, in which case the output is, again, the hash code of the
array.
Aah, ya gots me.
Yes, in this case, you are largely stuffed. UNLESS you pay heed to my
super-wily suggestion:
public class ArrayWrapper extends AbstractList{
private Object[] array;
public ArrayWrapper(Object[] array) {
this.array = array;
}
@Override
public Object get(int index) {
Object object = array[index];
if (object instanceof Object[]) object = new ArrayWrapper((Object[]) object);
return object;
}
@Override
public int size() {
return array.length;
}
}
Try:
System.out.println(new ArrayWrapper(new Object[][] {{1, 2, 3}, {'a', 'b', 'c'}, {true, false, true}}));
This only works with arrays of objects, but you could write a family of
specialised versions for arrays of primitives, and create the appropriate
one in the getter.
On 19 Lug, 13:53, Tom Anderson <t...@urchin.earth.li> wrote:
On Mon, 19 Jul 2010, Simone wrote:
Is there a way to rewrite the "implicit" toString() method for arrays,
so that I can write System.out.println( "v =" + vector ) and obtain the
output: v = (1,2,3,4) ?
Sadly not.
The best sticking-plaster is usually to wrap the array in a list:
System.out.println(Arrays.asList(vector));
That method returns a lightweight wrapper around the array that, amongst
other things, implements a more sensible toString.
--
I drink quarts and cans and bottles and sixes; between the turntables
keep the vodka and the mixes. -- MCA