Casting Object[]

W

Will Clark

Hi :eek:)

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 :eek:)

And if you don't understand what I going on about, just shout! (hehe) and
I'll try and explain better!


Will
 
D

David Zimmerman

Will said:
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?

java.lang.reflect.Array.newInstance(Class componentType, int dimension)
 
W

Will Clark

Thankyou so much!


David Zimmerman said:
Will said:
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?

java.lang.reflect.Array.newInstance(Class componentType, int dimension)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top