0

I am working on a game and I am using an array of Chunks to store loaded Chunks. Currently, I am working on terrain generation when the player spawns in. Is there any way possible that I can create a new Chunk in the chunk array whenever I see fitting. Long story short, when the player walks to a region where a chunk is not generated, I want to initialize a new value in the chunk array WITHOUT having to initialize that Chunk in the beginning of the class.

chunks = new Chunk[chunkCounter];
chunks[chunkCounter] = new Chunk();
chunkCounter++;

Every time a new Chunk needs to be generated I need to do something like this where I create a new Chunk in the array without the size of the array being previously stated.

Thanks in advance.

toniedzwiedz
  • 17,895
  • 9
  • 86
  • 131
Sock314
  • 157
  • 9
  • If I understand your question correctly, then the answer is yes: You can assign arbitrary new object instances to a variable at any position at any time during program execution. – Kon Jul 12 '14 at 16:20
  • 2
    Sure. Are you sure you want an array and not a list, though? – Dave Newton Jul 12 '14 at 16:21
  • I think you'd get better long-term performance if you used a [LinkedList](http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html). Reason being that you can arbitrarily scale it as you desire, but unlike some of the alternative `List` implementations, it does not require contiguous memory. [See here for a good explanation](http://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist) (there are some sacrifices if you do this, however, also explained there). – nerdwaller Jul 12 '14 at 16:34

1 Answers1

1

Yes you can do that! But prior to doing that you need to define the total size of your chunk array(lets say 100).

Chunk chunks = new Chunk[100];

You dont need to initialize it right away. When player comes to that chunk you can initialize it.

chunks[chunkCounter] = new Chunk();
chunkCounter++;

but mind you cannot do

chunks = new Chunk[chunkCounter];
chunks[chunkCounter] = new Chunk();
chunkCounter++;

as first like will create an array of size chunkCounter and the available indexes are 0-(chunkCounter-1) So your chunks[chunkCounter] = new Chunk(); will throw IndexOutofBoundException.

Also you cannot dynamically resize array. If you want use List instead.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289