Daksh Shah
Daksh Shah

Reputation: 3113

Dynamic array in java

What i am trying to do is

...
int sum[];
...
for(int z.....){
   ...
   sum[z] = some_random_value;
   ...
}

But it gives an error at line sum[z]=ran; that variable sum might not have been initialized.

I tried int sum[] = 0; instead of int sum[]; but even that gave an error. (I am basically a C programmer)

Upvotes: 2

Views: 18654

Answers (5)

Suresh Atta
Suresh Atta

Reputation: 121998

int sum[]= new int[length];

You haven't initialized. As of now , you just declared.

And do not for get that the length of the array should decide at the time of initialization.

Even if you do int sum[] = null; you'll end up with an NullPointerException while you do sum[z]=ran;

Can't i just keep it dynamic? the length is variable

No. Arrays lenght should be fixed while initializing it. Look into Collection's in java. More specifically A List interface with ArrayList implementation, which is

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null.

By writing int[] anArray = new int[10]; you are telling that

Allocate an array with enough memory for 10 integer elements and assigns the array to the anArray variable.

Seems you are new to array's and even for java. The tutorial may help you better to understand. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Upvotes: 2

Krease
Krease

Reputation: 16215

You still need to initialize your array after it's declared: int sum[]= new int[length];.

Now you can assign values in the array up to the size specified when you initialized it.

If you want to have a dynamically sized array, use ArrayList and call toArray at the end to convert it back to a regular array.

Upvotes: 1

user1134181
user1134181

Reputation:

If you're talking about dynamic arrays, the class can be represented as -

public class DynArray {
    private int size; // The current size of the array (number of elements in the array)
    private int maxSize; // Size of memory allocated for the array
    private Object[] array; // size of array == maxSize  

    /**
     * An array constructor
     * Argument specifies how much memory is needed to allocate for elements 
     * 
     * @param sz
     * @throws IndexOutOfBoundsException
     */
    public DynArray(int sz) throws IndexOutOfBoundsException {
        // Here called another more general constructor
        this(sz, sz, null);
    }
    /**
     * Call the constructor, in which indicated how much memory is allocated 
     * for the elements and how much memory is allocated total.
     * 
     * @param sz
     * @param maxSz
     * @throws IndexOutOfBoundsException
     */
    public DynArray(int sz, int maxSz) throws IndexOutOfBoundsException {
        // Here called another more general constructor     
        this(sz, maxSz, null);
    }
    /**
     * Additional argument contains an array of elements for initialization
     * 
     * @param sz
     * @param maxSz
     * @param iniArray
     * @throws IndexOutOfBoundsException
     */
    public DynArray(int sz, int maxSz, Object[] iniArray) throws IndexOutOfBoundsException {
        if((size = sz) < 0) { 
            throw new IndexOutOfBoundsException("Negative size: " + sz);
        }

        maxSize = (maxSz < sz ? sz : maxSz);
        array = new Object[maxSize]; // memory allocation

        if(iniArray != null) { // copying items
            for(int i = 0; i < size && i < iniArray.length; i++) {
                array[i] = iniArray[i];
                // Here it was possible to use the standard method System.arraycopy
            }
        }
    }
    /**
     * Indexing
     * 
     * @param i
     * @return
     * @throws IndexOutOfBoundsException
     */
    public Object elementAt(int i) throws IndexOutOfBoundsException {
        if (i < 0 || i >= size) {
            throw new IndexOutOfBoundsException("Index" + i + 
                    " out of range [0," + (size - 1) + "]");
        }
        return array[i];
    }
    /**
     * Changing the current size of the array. argument delta specifies
     * direction of change (positive - increase the size;
     * negative -  decrease the size)
     * 
     * @param delta
     */
    public void resize(int delta) {
        if (delta > 0) enlarge(delta); // increasing the size of the array 
        else if (delta < 0) shrink(-delta); // decreasing the size of the array
    }
    /**
     * Increasing the size of the array
     * 
     * @param delta
     */
    public void enlarge(int delta) {
        if((size += delta) > maxSize) { 
            maxSize = size;
            Object[] newArray = new Object[maxSize];

            // copying elements
            for(int i =0; i < size - delta; i++)
                newArray[i] = array[i];

            array = newArray;
        }
    }
    /**
     * Decreasing the size of the array
     * 
     * @param delta
     */
    public void shrink(int delta) {
        size = (delta > size ? 0 : size - delta);
    }
    /**
     * Adding a new element
     * (with a possible increasing the size of the array)
     * 
     * @param e
     */
    public void add(Object e) {
        resize(1);
        array[size-1] = e;
    }   
    /**
     * Removing the given value - shifting elements and subsequent 
     * reduction the size of the array
     * 
     * @param e
     */
    public void remove(Object e) {
        int j;
        for(j = 0; j < size; j++) {
            if(e.equals(array[j])) {
                break;
            }
        }

        if(j == size) {
            return false;
        } else {
            for(int k = j; k < size; k++) 
                array[k] = array[k + 1]; 

            resize(-1);
            return true;
        }
    }
}

Upvotes: 1

Makoto
Makoto

Reputation: 106390

An array of dynamic size isn't possible in Java - you have to either know the size before you declare it, or do resizing operations on the array (which can be painful).

Instead, use an ArrayList<Integer>, and if you need it as an array, you can convert it back.

List<Integer> sum = new ArrayList<>();
for(int i = 0; i < upperBound; i++) {
    sum.add(i);
}
// necessary to convert back to Integer[]
Integer[] sumArray = sum.toArray(new Integer[0]); 

Upvotes: 11

Juvanis
Juvanis

Reputation: 25950

This is for getting rid of compile-time error:

int sum[] = null;

However, to prevent runtime-errors I strongly suggest you to initialize your array like this:

int[] sum = new int[10];

The number in brackets denotes the array size.

And if your size is dynamic, then use a List implementation, such as ArrayList.

Upvotes: 4

Related Questions