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.
views:
55answers:
3Use something from the collections library, like a vector or an ArrayList.
You can create a new array when you run out of space, then use arraycopy to copy the old elements to the new.
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.