tags:

views:

55

answers:

3

Java - How do you read binary objects into an object array without knowing the size beforehand? For example, I don't know how many "clients" are within a binary file so how do I read them into an array without knowing the size beforehand? I know I could probably use vector but I have to use an array.

A: 

Use something from the collections library, like a vector or an ArrayList.

denis
Read the question.
Matthew Flaschen
My answer is pretty much the same as the one that was upvoted, why am i being voted down?
denis
bmargulies didn't recommend /using/ ArrayList. He explained the internal implementation so the OP could replicate it.
Matthew Flaschen
How does that equate to me needing to read the question? Its also quite clear that while bmargulies explained how ArrayLists work, he was also advocating their use.
denis
+1  A: 

You can create a new array when you run out of space, then use arraycopy to copy the old elements to the new.

Matthew Flaschen
+2  A: 

When you create an ArrayList, it creates a T[] of the reserved size.

When you add one too many items, it makes a new, larger T[] and uses System.arraycopy to move the contents.

For an unbounded number of possible inputs, this is the best you can do. You can even read the source of ArrayList to watch it being done.

Another possible solution applies when you can guarantee a maximum possible size, even if you don't know what the actual size is. You make an array as big as the maximum, put things into it. When done, create the final array of the actual size, and copy.

bmargulies