add an element to int [] array in java [duplicate]

Want to add or append elements to existing array

int[] series = {4,2};

now i want to update the series dynamically with new values i send..

like if i send 3 update series as int[] series = {4,2,3};

again if i send 4 update series as int[] series = {4,2,3,4};

again if i send 1 update series as int[] series = {4,2,3,4,1}; so on

How to do it????

I generate an integer every 5 minutes in some other function and want to send to update the int[] series array..


The length of an array is immutable in java. This means you can't change the size of an array once you have created it. If you initialised it with 2 elements, its length is 2. You can however use a different collection.

List<Integer> myList = new ArrayList<Integer>();
myList.add(5);
myList.add(7);

And with a wrapper method

public void addMember(Integer x) {
    myList.add(x);
};

try this

public static void main(String[] args) {
    int[] series = {4,2};
    series = addElement(series, 3);
    series = addElement(series, 1);
}

static int[] addElement(int[] a, int e) {
    a  = Arrays.copyOf(a, a.length + 1);
    a[a.length - 1] = e;
    return a;
}

If you are generating an integer every 5 minutes, better to use collection. You can always get array out of it, if required in your code.

Else define the array big enough to handle all your values at runtime (not preferred though.)


You'll need to create a new array if you want to add an index.

Try this:

public static void main(String[] args) {
    int[] series = new int[0];
    int x = 5;


    series = addInt(series, x);

    //print out the array with commas as delimiters
    System.out.print("New series: ");
    for (int i = 0; i < series.length; i++){
        if (i == series.length - 1){
            System.out.println(series[i]);
        }
        else{
            System.out.print(series[i] + ", ");
        }
    }
}

// here, create a method

public static int[] addInt(int [] series, int newInt){
    //create a new array with extra index
    int[] newSeries = new int[series.length + 1];

    //copy the integers from series to newSeries    
    for (int i = 0; i < series.length; i++){
        newSeries[i] = series[i];
    }
//add the new integer to the last index     
    newSeries[newSeries.length - 1] = newInt;



    return newSeries;

     }

Like others suggested you are better off using collection. If you however for some reason must stick to array then Apache Commons ArrayUtils may help:

int[] series = {4,2};
series = ArrayUtils.add(series, 3); // series is now {4,2,3}
series = ArrayUtils.add(series, 4); // series is now {4,2,3,4};

Note that the add method creates a new array, copies the given array and appends the new element at the end, which may have impact on performance.