59

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

Kiran
  • 3,095
  • 5
  • 23
  • 38
  • 5
    if the amount of items in series is not bounded you should really consider changing you design to use a more appropriate data structure such as [Vector](http://docs.oracle.com/javase/6/docs/api/java/util/Vector.html) or [List](http://docs.oracle.com/javase/6/docs/api/java/util/List.html) – Oren Apr 09 '13 at 10:41

14 Answers14

92

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);
};
flavian
  • 28,161
  • 11
  • 65
  • 105
58

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;
}
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • this looks inefficient, don't it? @Jason answer seems better to me – Alwin Kesler Feb 13 '17 at 20:15
  • @AlwinKesler I'm just curious here, how is this answer less efficient than @Jason's loop? `Array.copyOf()` basically calls `System.arraycopy()` which uses native code to copy an array. I haven't tested it myself but I would imagine it would be faster. – Hendra Anggrian Mar 08 '17 at 18:06
  • It create a new array in every request to `addElement`. This makes me think of a **log(N+1)** problem. Jason's uses an initial capacity and adds elements to the indexes which I think it's better. That's my opinion, still haven't test it – Alwin Kesler Mar 09 '17 at 23:11
  • @AlwinKesler I think it depends on what you have to do. Arrays are more efficients when you have to do a lot of searching; List are better for its dinamically nature. – Kyrol Apr 03 '17 at 08:32
  • nice point @kyrol – Alwin Kesler Apr 03 '17 at 18:11
  • If you need an array type as the result, and will only add one element each time, this is the best option – Gibolt Jul 18 '19 at 23:19
14

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

Sudhanshu Umalkar
  • 4,174
  • 1
  • 23
  • 33
11

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;

     }
Didi Bui
  • 623
  • 2
  • 7
  • 17
8

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.

Bunarro
  • 1,550
  • 1
  • 13
  • 8
7

You could also try this.

public static int[] addOneIntToArray(int[] initialArray , int newValue) {

    int[] newArray = new int[initialArray.length + 1];
    for (int index = 0; index < initialArray.length; index++) {
        newArray[index] = initialArray[index];
    }

    newArray[newArray.length - 1] = newValue;
    return newArray;
}
S4beR
  • 1,872
  • 1
  • 17
  • 33
4

The size of an array can't be changed. If you want a bigger array you have to create a new array.

However, a better solution would be to use an (Array)List which can grow as you need it. The method ArrayList.toArray(T[] a) returns an array if you need to use an array in your application.

Erik Pragt
  • 13,513
  • 11
  • 58
  • 64
3
public int[] return_Array() {

int[] a =new int[10];   
int b = 25;
for(int i=0; i<10; i++) {               
    a[i] = b * i;
    }
return a;

}
Lakshmi Prasanna
  • 347
  • 1
  • 2
  • 9
2
import java.util.Arrays;

public class NumberArray {     

    public static void main(String []args){
        int[] series = {4,2};
        int[] newSeries = putNumberInSeries(1,series);
        System.out.println(series==newSeries);//return false. you won't get the same int[] object. But functionality achieved.
    }
    private static int[] putNumberInSeries(int i, int[] series) {
        int[] localSeries = Arrays.copyOf(series, series.length+1);
        localSeries[series.length] = i;
        System.out.println(localSeries);
        return localSeries;
    }
}
AmitG
  • 10,365
  • 5
  • 31
  • 52
2

The ... can only be used in JDK 1.5 or later. If you are using JDK 4 or lower, use this code:'

public static int[] addElement(int[] original, int newelement) {
    int[] nEw = new int[original.length + 1];
    System.arraycopy(original, 0, nEw, 0, original.length);
    nEw[original.length] = newelement;
}

otherwise (JDK 5 or higher):

public static int[] addElement(int[] original, int... elements) { // This can add multiple elements at once; addElement(int[], int) will still work though.
    int[] nEw = new int[original.length + elements.length];
    System.arraycopy(original, 0, nEw, 0, original.length);
    System.arraycopy(elements, 0, nEw, original.length, elements.length);
    return nEw;
}

Of course, as many have mentioned above, you could use a Collection or an ArrayList, which allows you to use the .add() method.

hyper-neutrino
  • 5,272
  • 2
  • 29
  • 50
2
class AddElement {
     public static void main(String s[]) {
        int arr[] ={2,3};
        int add[] = new int[arr.length+1];
        for(int i=0;i<add.length;i++){
        if(i==add.length-1){
            add[i]=4;
        }else{
            add[i]=arr[i];
        }
        System.out.println(add[i]);
        }
    } 
}
Ankit Giri
  • 21
  • 1
2

This works for me:

int[] list = new int[maximum];
for (int i = 0; i < maximum; i++{
    list[i] = put_input_here;
}

This way, it's simple, yet efficient.

Herpy_Derp
  • 21
  • 1
1

similar to Evgeniy:

int[] series = {4,2};

  add_element(3);
  add_element(4);
  add_element(1);


public void add_element(int element){
  series = Arrays.copyOf(series, series.length +1);
  series[series.length - 1] = element;
}
Maksym Gontar
  • 22,765
  • 10
  • 78
  • 114
tom
  • 11
  • 1
1

int[] oldArray = {1,2,3,4,5};

    //new value
    int newValue = 10;

    //define the new array
    int[] newArray = new int[oldArray.length + 1];

    //copy values into new array
    for(int i=0;i < oldArray.length;i++)
        newArray[i] = oldArray[i];
    //another solution is to use 
    //System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);

    //add new value to the new array
    newArray[newArray.length-1] = newValue;

    //copy the address to the old reference 
    //the old array values will be deleted by the Garbage Collector
    oldArray = newArray;
Chandu D
  • 505
  • 3
  • 17