W
Will Clark
Hi
)
I've created a useful routine that "appends" an Object on to the end of an
array of Object, creating a new array with slack space if there is not
enough space available (sort of like a light-weight Vector):
public static final Object[] append(Object[] buf, int buf_len, Object addxn,
int slack)
{
Object[] ptr = buf;
if (buf == null || (buf_len + 1) > buf.length)
{
ptr = new Object[buf_len + 1 + slack];
if (buf != null) System.arraycopy(buf, 0, ptr, 0, buf_len);
}
ptr[buf_len] = addxn;
return ptr;
}
Anyway, this works fine, no probs, etc.
I am having problems, however, casting Object[] onto String[] or any other
such cast. Even if, obviously, all the elements of the array are String.
Now, I can state straight off where the problem lies. If I choose a large
enough String[] buffer so that the appended String fits inside it, then the
returned array can be cast back onto String[] - however, if the buffer is
exceeded, and line 6 is executed (creating a new buffer) then it can no
longer be cast back onto String[].
Does that make sense?
Anyway, the question! Is there any way of creating an Object[] array
generically which is of the same type as the original array. In other words,
it would create a new String[] array or Color[] or Rectangle[] or whatever
as appropriate?
Is there a way of doing it by reflection??? (perhaps)
Cheers
)
And if you don't understand what I going on about, just shout! (hehe) and
I'll try and explain better!
Will
I've created a useful routine that "appends" an Object on to the end of an
array of Object, creating a new array with slack space if there is not
enough space available (sort of like a light-weight Vector):
public static final Object[] append(Object[] buf, int buf_len, Object addxn,
int slack)
{
Object[] ptr = buf;
if (buf == null || (buf_len + 1) > buf.length)
{
ptr = new Object[buf_len + 1 + slack];
if (buf != null) System.arraycopy(buf, 0, ptr, 0, buf_len);
}
ptr[buf_len] = addxn;
return ptr;
}
Anyway, this works fine, no probs, etc.
I am having problems, however, casting Object[] onto String[] or any other
such cast. Even if, obviously, all the elements of the array are String.
Now, I can state straight off where the problem lies. If I choose a large
enough String[] buffer so that the appended String fits inside it, then the
returned array can be cast back onto String[] - however, if the buffer is
exceeded, and line 6 is executed (creating a new buffer) then it can no
longer be cast back onto String[].
Does that make sense?
Anyway, the question! Is there any way of creating an Object[] array
generically which is of the same type as the original array. In other words,
it would create a new String[] array or Color[] or Rectangle[] or whatever
as appropriate?
Is there a way of doing it by reflection??? (perhaps)
Cheers
And if you don't understand what I going on about, just shout! (hehe) and
I'll try and explain better!
Will