Search code examples
javaandroidopengl-esinputstreamdynamic-memory-allocation

Filling in uninitialized array in java? (or workaround!)


I'm currently in the process of creating an OBJ importer for an opengles android game. I'm relatively new to the language java, so I'm not exactly clear on a few things.

I have an array which will hold the number of vertices in the model(along with a few other arrays as well):

float vertices[];

The problem is that I don't know how many vertices there are in the model before I read the file using the inputstream given to me.

Would I be able to fill it in as I need to like this?:

vertices[95] = 5.004f; //vertices was defined like the example above

or do I have to initialize it beforehand?

if the latter is the case then what would be a good way to find out the number of vertices in the file? Once I read it using inputstreamreader.read() it goes to the next line until it reads the whole file. The only thing I can think of would be to read the whole file, count the number of vertices, then read it AGAIN the fill in the newly initialized array.

Is there a way to dynamically allocate the data as is needed?


Solution

  • You can use an ArrayList which will give you the dynamic size that you need.

       List<Float> vertices = new ArrayList<Float>();
    

    You can add a value like this:

       vertices.add(5.0F);
    

    and the list will grow to suit your needs.

    Some things to note: The ArrayList will hold objects, not primitive types. So it stores the float values you provide as Float objects. However, it is easy to get the original float value from this.

    If you absolutely need an array then after you read in the entire list of values you can easily get an array from the List.

    You can start reading about Java Collections here.