add an element to int [] array in java

JavaArrays

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

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;

     }

Solution 5 - Java

Like others suggested you are better off using collection. If you however for some reason must stick to array then Apache Commons https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/ArrayUtils.html">ArrayUtils</a> 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.

Solution 6 - Java

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

Solution 7 - Java

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.

Solution 8 - Java

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;

}

Solution 9 - Java

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

Solution 10 - Java

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.

Solution 11 - Java

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

Solution 12 - Java

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.

Solution 13 - Java

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

Solution 14 - Java

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKiranView Question on Stackoverflow
Solution 1 - JavaflavianView Answer on Stackoverflow
Solution 2 - JavaEvgeniy DorofeevView Answer on Stackoverflow
Solution 3 - JavaSudhanshu UmalkarView Answer on Stackoverflow
Solution 4 - JavaDidi BuiView Answer on Stackoverflow
Solution 5 - JavaBunarroView Answer on Stackoverflow
Solution 6 - JavaJason IveyView Answer on Stackoverflow
Solution 7 - JavaErik PragtView Answer on Stackoverflow
Solution 8 - JavaLakshmi PrasannaView Answer on Stackoverflow
Solution 9 - JavaAmitGView Answer on Stackoverflow
Solution 10 - Javahyper-neutrinoView Answer on Stackoverflow
Solution 11 - JavaAnkit GiriView Answer on Stackoverflow
Solution 12 - JavaHerpy_DerpView Answer on Stackoverflow
Solution 13 - JavatomView Answer on Stackoverflow
Solution 14 - JavaChandu DView Answer on Stackoverflow