Search code examples
javaarraysarraylisttheory

Data Types on the fly


Is it possible to dynamically declare arrays or variables after compilation? I ask because it is the only way I can think to solve this problem I've been running in to.

What I am trying to do is take an arbitrarily large set of numbers, find the midrange, and divide that set into two smaller subsets. Kinda like a quicksort (which I have no idea how to implement by the way).

The reason I believe Ill need to be able to declare these datatypes after compilation is because I want to be able to create an arbitrary amount of subsets as well, based off user input.

So, for example if the user specifies 8 levels then the program should be able to divide the original set with the method described above, and repeat that with all the subsequent subsets. It appears, to me that in order to organize the numbers in this way would require the use of arrays, hence the problem I'm running into.

Is there a simpler way to approach this problem? If there is I'd really appreciate some insight. And if not, how can I do what I described above?

To clarify, I am writing this program in Java, and no, this is not a homework assignment.

Thanks a bunch.


Solution

  • You can do this with a 2D array (which is an array of arrays). This initial declaration might be:

    int[][]  array;
    

    When you know how many subarrays you'll need, you can create the array with one known dimension:

    array = new int[8][];
    

    You have now created an array that can hold 8 subarrays of type int[], but the subarrays don't yet exist. To create one, you can do this:

    array[0] = new int[15];
    array[1] = new int[12];
    // etc.
    

    Note that each subarray can be of a different size if you want.