- Java append element to primitive array
- 2 Answers 2
- How to add an element at the end of an array?
- 6 Answers 6
- Add element into array java
- 7 Answers 7
- Java – Append to Array
- Append Element to Array
- Append Array to Array
- Append Element to Array using ArrayList
- Append Element to Array using java.util.Arrays
- Conclusion
Java append element to primitive array
Is it possible to append elements at the end of a primitive array in Java? For ex: if int[] a = new int[10]; is an array. How can i go on appending elements at the end? Edit:
I do not want to use ArrayList for performance reason and want to stay with primitive arrays.
What do you mean by «append» ? having them objects one-after-another in memory space ? simply being able to print the members of the array with the additional object ? increase the size of the array and add more elements ? do you want to add elements of different type ?
2 Answers 2
A way to make an Array more dynamic is to create a method that creates a new longer array and replace the old one with it.
lets say you have an int[] of size 10 and it holds numbers 0 to 9:
int[] array = new int[10]; for(int i = 0; i < array.length; i++) array[i] = i;
Printing the contents of the array will output: 0 1 2 3 4 5 6 7 8 9
Now you can have a method like this:
private int[] appendArray(int[] array, int x)
array = appendArray(array, 10);
Now printing the contents of the array will output: 0 1 2 3 4 5 6 7 8 9 10
Alternatively you can use an ArrayList that is basically doing a similar thing.
Once created, the size of an array in Java is fixed.
If you want to have a dynamically sized storage, you will want to use an ArrayList .
The alternative is to create a new (larger) array and copy the contents of the old one, but keep in mind that this will be very expensive in both time and memory:
// this is a terrible idea, don't do it public int[] append(int[] i, int newElement)
This is effectively what an ArrayList is doing for you behind the scenes (albeit more efficiently), so if you're going to be adding very many elements, you'll want to start with a larger ArrayList than the default capacity of 10 elements.
How to add an element at the end of an array?
I want to know how to add or append a new element to the end of an array. Is any simple way to add the element at the end? I know how to use a StringBuffer but I don't know how to use it to add an element in an array. I prefer it without an ArrayList or list. I wonder if the StringBuffer will work on integers.
Arrays are fixed length. If you want to add items to the end, use something expandable, like a List .
An ArrayList is to an array what a StringBuffer is to a String . If you want to append elements and get an array as a result instead of a String , then you do want to use a ArrayList
6 Answers 6
You can not add an element to an array, since arrays, in Java, are fixed-length. However, you could build a new array from the existing one using Arrays.copyOf(array, size) :
public static void main(String[] args) < int[] array = new int[] ; System.out.println(Arrays.toString(array)); array = Arrays.copyOf(array, array.length + 1); //create new array from old array and allocate one more element array[array.length - 1] = 4; System.out.println(Arrays.toString(array)); >
I would still recommend to drop working with an array and use a List .
Arrays in Java have a fixed length that cannot be changed. So Java provides classes that allow you to maintain lists of variable length.
Generally, there is the List interface, which represents a list of instances of the class T . The easiest and most widely used implementation is the ArrayList . Here is an example:
List words = new ArrayList(); words.add("Hello"); words.add("World"); words.add("!");
List.add() simply appends an element to the list and you can get the size of a list using List.size() .
And for those times when you really do need an array of your objects, the List class has toArray() and toArray(T[] t) .
To clarify the terminology right: arrays are fixed length structures (and the length of an existing cannot be altered) the expression add at the end is meaningless (by itself).
What you can do is create a new array one element larger and fill in the new element in the last slot:
public static int[] append(int[] array, int value)
This quickly gets inefficient, as each time append is called a new array is created and the old array contents is copied over.
One way to drastically reduce the overhead is to create a larger array and keep track of up to which index it is actually filled. Adding an element becomes as simple a filling the next index and incrementing the index. If the array fills up completely, a new array is created with more free space.
And guess what ArrayList does: exactly that. So when a dynamically sized array is needed, ArrayList is a good choice. Don't reinvent the wheel.
The OP says, for unknown reasons, "I prefer it without an arraylist or list."
If the type you are referring to is a primitive (you mention integers, but you don't say if you mean int or Integer ), then you can use one of the NIO Buffer classes like java.nio.IntBuffer . These act a lot like StringBuffer does - they act as buffers for a list of the primitive type (buffers exist for all the primitives but not for Objects), and you can wrap a buffer around an array and/or extract an array from a buffer.
Note that the javadocs say, "The capacity of a buffer is never negative and never changes." It's still just a wrapper around an array, but one that's nicer to work with. The only way to effectively expand a buffer is to allocate() a larger one and use put() to dump the old buffer into the new one.
If it's not a primitive, you should probably just use List , or come up with a compelling reason why you can't or won't, and maybe somebody will help you work around it.
As many others pointed out if you are trying to add a new element at the end of list then something like, array[array.length-1]=x; should do. But this will replace the existing element.
For something like continuous addition to the array. You can keep track of the index and go on adding elements till you reach end and have the function that does the addition return you the next index, which in turn will tell you how many more elements can fit in the array.
Of course in both the cases the size of array will be predefined. Vector can be your other option since you do not want arraylist, which will allow you all the same features and functions and additionally will take care of incrementing the size.
Coming to the part where you want StringBuffer to array. I believe what you are looking for is the getChars(int srcBegin, int srcEnd,char[] dst,int dstBegin) method. Look into it that might solve your doubts. Again I would like to point out that after managing to get an array out of it, you can still only replace the last existing element(character in this case).
Add element into array java
Little known fact, you can use Arrays.binarySearch to find the index of where you should insert it (docs.oracle.com/javase/6/docs/api/java/util/Arrays.html).
You are on the right track with what you tried, but after copying over the value you want to add, you need to append the end of the original array.
7 Answers 7
As this is something you should accomplish yourself, I will only provide the method to implement it, not the code:
If you would set the number at position index , you would overwrite the value that was there previously. So what you need to do is move every element one position towards the end of the array starting from index : num[x] becomes num[x+1] , etc.
You will find out that you need to do this in reverse order, otherwise you will fill your array with the value in num[index] .
During this process you will need to decide what to do with the last entry of the array ( num[num.length - 1] ):
- You could just overwrite it, discarding the value
- You could return it from your function
- You could throw an exception if it is non-zero
- You could create a new array that is 1 entry larger than the current array instead to keep all values
- etc.
After this, you have duplicated num[index] : the value is present in num[index+1] , too, as you have moved it away.
Now it is possible to write the new value at the desired position without overriding an existing value.
You have several errors in your code:
- You increment k , you need to decrement it ( k-- , not k++ )
- You modify k again in your loop body: it is updated twice in each cycle
- If you start with k = num.length , you will try to write at num[num.length + 1] , which is not possible
Java – Append to Array
In Java, an array is a collection of fixed size. You cannot increase or decrease its size. But, you can always create a new one with specific size.
To append element(s) to array in Java, create a new array with required size, which is more than the original array. Now, add the original array elements and element(s) you would like to append to this new array.
Also, you can take help of Arrays class or ArrayList to append element(s) to array. But, these techniques require conversion from array to ArrayList, and vice versa.
In this tutorial, we will go through different approaches with the examples, to append one or more elements to the given array.
Append Element to Array
In this example, we will add an element to array.
We shall implement the following steps.
- Take original array arr . (We shall initialize an array with some elements.)
- Take the element you would to append to array arr .
- Create new array arrNew with size greater than that of arr by one.
- Assign elements of arr and element to arrNew . We will use for loop to assign elements of arr to arrNew .
Java Program
public class Example < public static void main(String[] args) < String arr[] = ; String element = "mango"; String arrNew[] = new String[arr.length + 1]; int i; for(i = 0; i < arr.length; i++) < arrNew[i] = arr[i]; >arrNew[i] = element; //print new array for(String s: arrNew) < System.out.println(s); >> >
apple banana cherry mango
Append Array to Array
In this example, we will add an array to another array and create a new array.
We shall implement the following steps.
- Take two input arrays arr1 and arr2.
- Create new array arrNew with size equal to sum of lengths of arr1 and arr2.
- Assign elements of arr1 and arr2 to arrNew. Use for loop to assign elements of input arrays to new array.
Java Program
public class Example < public static void main(String[] args) < String arr1[] = ; String arr2[] = ; String arrNew[] = new String[arr1.length + arr2.length]; int i; for(i = 0; i < arr1.length; i++) < arrNew[i] = arr1[i]; >for(i = 0; i < arr2.length; i++) < arrNew[arr1.length + i] = arr2[i]; >//print new array for(String s: arrNew) < System.out.println(s); >> >
apple banana cherry mango grape
Append Element to Array using ArrayList
In this example, we will take help of ArrayList to append an element to array.
We shall implement the following steps.
- Take input array arr1.
- Create an ArrayList with elements of arr1.
- Append the element to the ArrayList.
- Convert ArrayList to array.
Java Program
import java.util.ArrayList; public class Example < public static void main(String[] args) < String arr[] = ; String element = "mango"; ArrayList arrayList = new ArrayList(); for(String s: arr) arrayList.add(s); arrayList.add(element); String arrNew[] = new String[arr.length + 1]; for(int i = 0; i < arrNew.length; i++) arrNew[i] = arrayList.get(i); //print new array for(String s: arrNew) System.out.println(s); >>
apple banana cherry mango
Append Element to Array using java.util.Arrays
In this example, we will use java.util.Arrays class to append an element to array.
We shall implement the following steps.
- Take input array arr1.
- Create a new array using java.util.Arrays with the contents of arr1 and new size.
- Assign the element to the new array.
Java Program
import java.util.Arrays; public class Example < public static void main(String[] args) < String arr[] = ; String element = "mango"; String arrNew[] = Arrays.copyOf(arr, arr.length + 1); arrNew[arr.length]= element; //print new array for(String s: arrNew) System.out.println(s); > >
apple banana cherry mango
Conclusion
In this Java Tutorial, we have learned how to append element(s) to array using different techniques with the help of example programs.