danem
danem

Reputation: 1515

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.

Upvotes: 1

Views: 169

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533720

I like using array but for creating sub sets or sub list using a list may be a better choice.

List<Integer> ints = new ArrayList<Integer>();
for(int i=0;i<128;i++) ints.add(i);

int subLists = 8;
int subListSize = (ints.size() + subLists - 1) / subLists;
List<List<Integer>> intsList = new ArrayList<List<Integer>>();
for(int i = 0; i < ints.size(); i += subListSize)
  intsList.add(ints.subList(i, Math.max(i+subListSize, ints.size())));

Upvotes: 0

Chris Nava
Chris Nava

Reputation: 6802

You are describing a recursive function.

Also, if you want something like an int[] but don't know the size at initialization time, an ArrayList will allow you to .add() any number of Integer objects.

Note that you said compile time and I said initialization time. You don't need to hard code the length of an array at compile time. It can be initialized with a variable like so:

int[] items = new int[x]();

Upvotes: 0

Stewart Murrie
Stewart Murrie

Reputation: 1319

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.

Upvotes: 2

Related Questions