Anonymous
Anonymous asked in Computers & InternetProgramming & Design · 3 weeks ago

Java array question?

I created a java array of length 100.

I have a for loop that adds items into the array by setting the position at an index to a new value.

My array is either too big or too small. How can I add items to an array and set its size to exactly the amount of numbers added without using arrayUtils or arraylists?

2 Answers

Relevance
  • 3 weeks ago

    A Java array object is created with a fixed size that can't be changed.  Unless you know in advance exactly how many entries you'll need (or get lucky guessing), it will always be either too big or too small.

    The only way to "change the size" of an existing array is to create a new (empty) array with the desired size, then copy entries from the old array into the new one, then replace any references to the old array with references to the new one.  That's not too difficult to code, but annoying to have to do every time you need a large array with little or no unused space.  That's why collections classes like ArrayList and utility classes like Arrays exist; so you don't have to write that sort of code every time.

    You'd almost never do this in a production program, so this must be a student exercise.   If you can't get the problem size before reading the input, then you have two choice: either read the input twice (once to count the number of entries and allocate the proper array size, and a second time to store the data), or reallocate as you read the data just once (increasing the size when you run out of room, then decreasing the size to just what's needed when all data has been read.)

    The first option is the only way to not, at some point, have a minimum of about twice the final array size allocated at some point during the program.  That's not always possible, since data may be coming from a user at a terminal or from a dynamic data source like some sort of scanning device or a database that's being updated by other processes.

    To code the second option, you might find it handy to make a static "resize()" utility method of your own.  That will accept an array and a new size, and:

      1.  Create a new array with the desired number of elements;

      2.  Copy the first n elements from the old array to the new one, where n is the

           smaller of the old and new sizes; and

      3.  Return the new array as a result.

    Code and test that, then you can experiment with different allocation strategies in your "main" program.  A very simple (and slow!) method might be:

        Scanner sysin = new Scanner(System.in);

        int[] data = new int[100];

        int used = 0;

        while (sysin.hasNextInt()) { // loop for as many integers are in System.in

            if (used >= data.length) { // make sure there's room for a new integer

                data = resize(data, used + 1);

            }

            data[used] = sysin.nextInt(); // store and count it

        }

        if (data.length > used) { // if there's unused space in the final array

            data = resize(data, used); // shrink to just the number of entries with data

        }

    Now you can work on your problem as two smaller subproblems.  You could even use "forbidden" classes/methods in an early version of resize(), just to get something that works while you debug your calling program, then rewrite resize() to conform to final "hand in" requirements.

  • Anonymous
    3 weeks ago

    create a variable SIZE or use a vector

Still have questions? Get your answers by asking now.