views:

76

answers:

5

I was wondering how to initialise an integer array such that it's size and values change through out the execution of my program, any suggestions?

+5  A: 

Yes: use ArrayList.

In Java, "normal" arrays are fixed-size. You have to give them a size and can't expand them or contract them; to change the size, you have to make a new array and copy the data you want, which is inefficient and a pain for you.

Fortunately, there are all kinds of built-in classes that implement common data structures, and other useful tools too. You'll want to check the Java 6 API for a full list of them.

One caveat: ArrayList can only hold objects (e.g. Integers), not primitives (e.g. ints). In MOST cases, autoboxing/autounboxing will take care of this for you silently, but you could get some weird behavior depending on what you're doing.

Lord Torgamus
Congratulations on reaching 1,000 reputation. Not that you gain much at 1,000.
R. Bemrose
@Power: Thanks! But yeah, not the hugest milestone. I can't think of an appropriately-sized celebration... maybe I'll ask on meta.
Lord Torgamus
A: 

You can't change the size of an array. You can, however, create a new array with the right size and copy the data from the old array to the new.

But your best option is to use IntList from jacarta commons. (http://commons.apache.org/primitives/api-release/org/apache/commons/collections/primitives/IntList.html)

It works just like a List but takes less space and is more efficient than that, because it stores int's instead of storing wrapper objects over int's (that's what the Integer class is).

Morgaelyn
A: 

How about using a List instead? For example, ArrayList<integer>

Konrad Garus
+1  A: 

Arrays are fixed size once instantiated. You can use a List instead.

Autoboxing make a List usable similar to an array, you can put simply int-values into it:

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
Mnementh
+2  A: 

Arrays in Java are of fixed size. What you'd need is an ArrayList, one of a number of extremely valuable Collections available in Java.

Instead of

Integer[] ints = new Integer[x]

you use

List<Integer> ints = new ArrayList<Integer>

Then to change the list you use ints.add(y) and ints.remove(z) amongst many other handy methods you can find in the appropriate Javadocs.

I strongly recommend studying the Collections classes available in Java as they are very powerful and give you a lot of builtin functionality that Java-newbies tend to try to rewrite themselves unnecessarily.

MattGrommes