1

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

7 Answers 7

6

To set the ith element in result to the ith 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);

See also:

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1
        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];

Comments

0

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]

Comments

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

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.