13 Replies Latest reply: Nov 20, 2009 3:04 PM by 843789 RSS

    How can I make a dynamic array of unknown initial size?

    843789
      Hello,

      I'm struggling with what is the best way to create a dynamic array of objects in java. I'm planning to read lines of text from a file, create objects containing lines from the text and populate an array with these objects.

      The problem I'm facing is that I can not create an empty array without specifying the size and if I create the array inside the method which reads from the file I need a way of accessing the array and also append to the array as it grows.

      I have looked over the arrayList class but I don't see how I can then use my methods directly on the arrayList. The way I'm thinking about doing this is something like this:
      myArrayOfObjects.myMethod(stringJustReadFromFile);
      The arrayList class don't seem to have this type of direct access, but instead will return the object at specified index.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
        • 1. Re: How can I make a dynamic array of unknown initial size?
          794258
          I don't remember how the code goes specifically, but if you're going to put each line in an array, you could use a method to get the number of lines in the file, then create the array with that size.

          Likewise, if you know how you want to divide the code (each line, each so many characters, etc.) you can use a method or combination of methods to figure out how many divisions there will be, then set the array size with that.

          Do you understand what I'm saying?
          • 2. Re: How can I make a dynamic array of unknown initial size?
            DrClap
            Can't figure out how to use a list? Like this:
            List<Thing> things= new ArrayList<Thing>();
            // code to populate the list goes here
            Banana bananaNumberTwo = things.get(2).getBanana();
            • 3. Re: How can I make a dynamic array of unknown initial size?
              3004
              Red_herring wrote:
              I have looked over the arrayList class but I don't see how I can then use my methods directly on the arrayList. The way I'm thinking about doing this is something like this:
              myArrayOfObjects.myMethod(stringJustReadFromFile);
              The arrayList class don't seem to have this type of direct access, but instead will return the object at specified index.
              You wouldn't use your methods directly on an ArrayList. The ArrayList holds references to your objects just like an array does.

              [http://java.sun.com/docs/books/tutorial/collections/index.html]
              • 4. Re: How can I make a dynamic array of unknown initial size?
                796262
                Red_herring wrote:
                Hello,

                I'm struggling with what is the best way to create a dynamic array of objects in java. I'm planning to read lines of text from a file, create objects containing lines from the text and populate an array with these objects.

                The problem I'm facing is that I can not create an empty array without specifying the size and if I create the array inside the method which reads from the file I need a way of accessing the array and also append to the array as it grows.

                I have looked over the arrayList class but I don't see how I can then use my methods directly on the arrayList. The way I'm thinking about doing this is something like this:
                myArrayOfObjects.myMethod(stringJustReadFromFile);
                The arrayList class don't seem to have this type of direct access, but instead will return the object at specified index.
                How is myArrayOfObjects[i] not returning an object at a specified index? What is the difference between that and the get(i) method that DrClap pointed out?
                • 5. Re: How can I make a dynamic array of unknown initial size?
                  843789
                  shadowayex wrote:
                  I don't remember how the code goes specifically, but if you're going to put each line in an array, you could use a method to get the number of lines in the file, then create the array with that size.

                  Likewise, if you know how you want to divide the code (each line, each so many characters, etc.) you can use a method or combination of methods to figure out how many divisions there will be, then set the array size with that.

                  Do you understand what I'm saying?
                  Thanks, I have made a method that gets the number of lines in the file which returns the required array size. But I don't see where I should declare my array, I get a "array dimension missing" error if I try to declare it empty.
                  • 6. Re: How can I make a dynamic array of unknown initial size?
                    843789
                    >
                    You wouldn't use your methods directly on an ArrayList. The ArrayList holds references to your objects just like an array does.
                    So I then need to create an object everytime I need to access it from the list? I guess I'm thinking in terms of an array of structs here, sorry ;-)
                    • 7. Re: How can I make a dynamic array of unknown initial size?
                      DrClap
                      Red_herring wrote:
                      Thanks, I have made a method that gets the number of lines in the file which returns the required array size. But I don't see where I should declare my array, I get a "array dimension missing" error if I try to declare it empty.
                      Then don't do that. Declare it with the correct size. Like this:
                      Thing[] things = new Thing[]; // wrong
                      Thing[] things = new Thing[numberOfThings]; // right
                      • 8. Re: How can I make a dynamic array of unknown initial size?
                        843789
                        kevinaworkman wrote:
                        How is myArrayOfObjects[i] not returning an object at a specified index? What is the difference between that and the get(i) method that DrClap pointed out?
                        Well, I guess I'm thinkin along the lines of that if the array contains reference variables I should be able to directly use my methods on the variable at index i.
                        • 9. Re: How can I make a dynamic array of unknown initial size?
                          794258
                          Let's say your method is numberOfLines(), do something like this:

                          int numberOfLines = myFile.numberOfLines();
                          MyArray[] myArray = new MyArray[numberOfLines];

                          The syntax may be off, as I just started Java programming, but the concept is there.
                          • 10. Re: How can I make a dynamic array of unknown initial size?
                            843789
                            DrClap wrote:
                            Then don't do that. Declare it with the correct size. Like this:
                            Thing[] things = new Thing[]; // wrong
                            Thing[] things = new Thing[numberOfThings]; // right
                            Thank you, I just tried this and it compiled fine. I have declared the array as private at the begining of my class containing main(). I then call getArraySize() from my constructor, I guess that I was a bit sceptic of how the order of things got executed in this scenario, but I guess the compiler figures it out.

                            Edited by: Red_herring on Nov 20, 2009 10:58 AM

                            Edited by: Red_herring on Nov 20, 2009 11:18 AM
                            • 11. Re: How can I make a dynamic array of unknown initial size?
                              3004
                              Red_herring wrote:
                              kevinaworkman wrote:
                              How is myArrayOfObjects[i] not returning an object at a specified index? What is the difference between that and the get(i) method that DrClap pointed out?
                              Well, I guess I'm thinkin along the lines of that if the array contains reference variables I should be able to directly use my methods on the variable at index i.
                              Thing arr[] = new Thing[10];
                              
                              for (int i = 0; i < arr.size; i++) {
                                arr[i] = new Thing();
                              }
                              
                              ...
                              
                              for (int i = 0; i < arr.size; i++) {
                                Thing thing = arr;
                              thing.doStuff();
                              }

                              // vs.

                              List<Thing> list = new ArrayList<Thing>();

                              for (int i = 0; i < 10; i++) {
                              list.add(new Thing());
                              }

                              ...

                              for (Thing thing : list) {
                              thing.doStuff();
                              }


                              There are other ways to access the items in the list. You could use an explicit Iterator. You could use get(), but that's really appropriate only for random access, not for iterating.
                              • 12. Re: How can I make a dynamic array of unknown initial size?
                                843789
                                Thanks jverd, it helped to see this exemplified.
                                • 13. Re: How can I make a dynamic array of unknown initial size?
                                  800308
                                  Red_herring wrote:
                                  shadowayex wrote:
                                  I don't remember how the code goes specifically, but if you're going to put each line in an array, you could use a method to get the number of lines in the file, then create the array with that size.

                                  Likewise, if you know how you want to divide the code (each line, each so many characters, etc.) you can use a method or combination of methods to figure out how many divisions there will be, then set the array size with that.

                                  Do you understand what I'm saying?
                                  Thanks, I have made a method that gets the number of lines in the file which returns the required array size. But I don't see where I should declare my array, I get a "array dimension missing" error if I try to declare it empty.
                                  You're missing a couple of key concepts... Firstly, declaring an array is not the same as initialising it. Both steps are commonly done in one step, though of course they don't have to be.

                                  Please read and try to understand the comments in this code. Please ask for clarification if you don't follow... it's probably my lack of skill at explaining stuff.

                                  *decare and initialise an array*
                                  package forums;
                                  
                                  class Thing
                                  {
                                    int id;
                                    String name;
                                  }
                                  
                                  /**
                                   * Declare and initialise an array of Things in one line of code. This is the
                                   * most succinct and simplest form of array declaration, and it is also the
                                   * most commonly used, but it can (and should) only be used when you know how
                                   * large the array needs to be when-and-where you declare the array. 
                                   *
                                   * If you do not know "the peak" number of items which will be stored in the
                                   * array then consider using a "dynamic data-structure" such as a List instead.
                                   * The standard Java API has a number of List implementations. 
                                   *
                                   * IMHO, The best "all round" List implementation is ArrayList, which (as the 
                                   * name suggests) is actually backed by an array "under the hood". ArrayList 
                                   * supports fast and efficient access both serialy (i.e. an Iterator) and 
                                   * randomly (i.e get(index)). But of course this flexibility comes at a cost,
                                   * which is the overhead of reallocating and copying the reference-list whenever
                                   * the backing-array needs to be "grown", which is inherently an O(n) operation.
                                   * But don't let this "inefficiency" put you off using an ArrayList, it's fast
                                   * enough in all but the "extreme" cases, and premature optimisation IS evil.
                                   */ 
                                  public class Stuff
                                  {
                                    public static void main(String[] args) {
                                      try {
                                        Thing[] array = new Thing[100];
                                        System.out.println(array.length);
                                      } catch (Exception e) {
                                        e.printStackTrace();
                                      }
                                    }
                                  }
                                  decare an array, then itialise it later
                                  package forums;
                                  
                                  class Thing
                                  {
                                    int id;
                                    String name;
                                  }
                                  
                                  /**
                                   * Declare an array of Things, and then itialise it later, in a seperate line. 
                                   * Do this when the array variable needs to have a wider scope then the code 
                                   * which initialises the array, especially the part of the code which works out
                                   * how large the array needs to be, as you must provide this "array capacity" 
                                   * when you initialise the array. Also note that Java arrays can itialised to
                                   * null. 
                                   *
                                   * The smart people in the class might have figured out allready that "under the
                                   * hood", Java treats an array as a special kind of object, hence every array
                                   * has a "length" attribute, which tells you it's current capacity.
                                   */ 
                                  public class Stuff
                                  {
                                    public static void main(String[] args) {
                                      Thing[] array = null;
                                      try {
                                        array = new Thing[100];
                                        System.out.println(array.length);
                                      } catch (Exception e) {
                                        System.out.println("array="+array);
                                        e.printStackTrace();
                                      }
                                    }
                                  }
                                  Cheers. Keith.