In the following piece of code, I have the result of a query, but I have no clue about the total number of records. I have to store it into a container. When I read each record of the container, it will be a simple loop so that index-based access will not be used.
List<MyObject> list;
while ( source.hasNext() ) {
MyObject ob = new MyObject();
convertObject(ob, source.next());
list.add(ob);
}
...
//Another method
for (MyObject ob : objects){
showThings(ob);
}
LinkedList is poor because it creates many small objects with pointers to the next one. It uses more memory, makes the memory more fragmented and has more cache miss.
ArrayList is poor because I don't know the number of records that I will insert. Whenever I insert a new item and the inner array is full, it will allocate a bigger block of memory and copy everything to the new block.
I didn't find any solution in java.util. So I consider writing a custom list. It will be like a LinkedList, but each cell is an array. In other words, the first node will be like an ArrayList, but when it is full and I insert a new object, it will create another node with an array to insert the new items instead of copying everything. However, I may be reinventing the wheel somehow.