124

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?

0

8 Answers 8

135

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I wonder why following code is right in java? int[] array = new int[size]; size is a variable, but the length of an array must be fixed, am I right?@Lord Torgamus
@jerry_sjtu yeah, the array doesn't change size to match size as the program goes on; it gets whatever size happens to be in size when that line is executed.
Whenever I remove an item from an ArrayList, I end up with a null at the end. Any ideas why?
@AaronFranke how do you remove the item, can you post your complete code here?
43

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.

2 Comments

want working till I tried: List<Integer> ints = new ArrayList<Integer>();
Why do you use List<Integer> instead of ArrayList<Integer>?
27

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

2 Comments

Why do you declare a reference variable of type List, and not ArrayList?
Because it allows you to simply switch between List-implementations if needed, you only have to change the new XYZList(). If the variable is declared as ArrayList oyu might use methods specific to this implementation, making a change more complicated.
12

I disagree with the previous answers suggesting ArrayList, because ArrayList is not a Dynamic Array but a List backed by an array. The difference is that you cannot do the following:

ArrayList list = new ArrayList(4);
list.put(3,"Test");

It will give you an IndexOutOfBoundsException because there is no element at this position yet even though the backing array would permit such an addition. So you need to use a custom extendable Array implementation like suggested by @randy-lance

2 Comments

I believe you wanted to link it to codereply.com/answer/6i5bur/java-dynamic-arrays.html
I am not sure if ArrayList has any put method as I see in Java8 source code. Just trying to find out how it behaves with given capacity. However found ArrayList.add() method.
7
  1. It is recommend to use List to deal with small scale size.

  2. If you have a huge number of numbers, NEVER use List and autoboxing,

    List< Integer> list

For every single int, a new Integer is auto created. You will find it getting slow when the size of the list increase. These Integers are unnecessary objects. In this case, to use a estimated size would be better,

int[] array = new int[ESTIMATED_SIZE];

Comments

4

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

Comments

4

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. (here)

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).

Comments

0
class Main {  
   
    public static void main(String[] args) {    
        int [] a={1, 0, 3, 4, 1, 2, 0, 4};    
        int count =1;  
        int [] temp = null;
        for(int r : a){
            if(r!=0){
                if(temp==null || count >= temp.length){
                    temp =dynamicincrement(count,temp);
                }
                temp[count-1] = r;
                count=count+1;
            }
        }

        System.out.println("the value"+Arrays.toString(temp));
    }

    public static  int [] dynamicincrement(int size,int [] existingdata){  
        int [] trf=new int [size];
        if(existingdata==null){
            return new int[size];
        }

        if( existingdata!=null  &&  existingdata.length>0){
            for(int i=0;i<existingdata.length;i++){
                trf[i]=existingdata[i];
            }
        }
        return trf;
    }

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.