Reputation: 13
I'm new to arrays in java, so my question might seem simple to all of u
I have two arrays:
int[] newarray = new int[] {1,2,3,4}
int[] result = new int[4] // array with space for 4 elements
i=0
My question is: How do I add elements from newarray to result? For example, how do i add newarray[i]? There seems to be no add function like in python unless you use ArrayLists. Also is it possible to add elements from an array to an arraylist, or doesn't they work together? Hope to get some clarification :)
Upvotes: 1
Views: 8088
Reputation: 62155
This should also work:
Arrays.asList(result).addAll(Arrays.asList(newarray));
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)
Using static imports:
asList(result).addAll(asList(newarray));
Upvotes: 0
Reputation: 47729
Either copy elements one at a time in a loop or use System.arraycopy
.
Understand that an array in Java is like an array in C in that it's fixed length (there are other classes like ArrayList for variable-length use). So you don't "add" a new element, you simply assign a value (x[i] = something;
) to an existing element (which was initialized to zero when the array was created).
To my knowledge there's no "add all elements of this array" method on ArrayList, so to do that you'd have to loop through the array and add the elements one at a time. There are methods to go the other direction.
Upvotes: 0
Reputation: 50858
To set the i
th element in result
to the i
th element in newarray
, do the following:
result[i] = newarray[i];
In addition, you can copy over the entirety of the array using arraycopy
:
System.arraycopy(newarray, 0, result, 0, newarray.length);
Upvotes: 6
Reputation: 19989
System.arraycopy(newarray, 0, result, 0, newarray.length);
or you can do it manually
for(int i = 0; i < newarray.length; i++) {
result[i] = newarray[i];
}
to work with Arrays, you can use
Arrays.asList(Object[] a);
Upvotes: 0
Reputation: 11958
int[] newarray = new int[] {1,2,3,4}
int[] result = new int[newarray.length];
for(int i=0;i<newarray.length;i++)
result[i]=newarray[i];
Upvotes: 1
Reputation: 178
Lets say you want to assign the third value in newarray to the third index in result. That would be like:
result[2] = newarray[2]
Upvotes: 0
Reputation: 4697
Use System.arrayCopy
to copy arrays. Example:
System.arraycopy(newarray, 0, result, 0, newarray.length)
The first argument is the source array, then the source position, then the destination array and destination position, and the length.
Upvotes: 1