2

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)

1
  • okay this problem is relatively simple one. First initialize an array with some length and populate it. always keep a check if array is full or not. If it's full create a new array instance with double the size. keep on doing it. Commented Feb 8, 2014 at 7:38

5 Answers 5

11

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]); 
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

2
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

4 Comments

Can't i just keep it dynamic? the length is variable
No, In java you cannot. That is fixed. You may want to look at Collections framework.
why int sum[]= new int[length]; and not int sum[length];
@DakshShah That's the syntax of how can an array declared :) .It is good to know that there are many ways to initialize an array too.
1

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;
        }
    }
}

2 Comments

I don't disagree, but this is not one of those times. Also note, your copying of elements in the originating array is inefficient; reference ArrayList's code to see more performant behavior.
The only time I can think of needing to re-implement such a type [over ArrayList] is for specialized types, such as int[] as a backing, but this is not doing that (and even those already exist) .. also, for the love of nominative typing, implement List.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.