Reputation: 35
So let's say I have an array: {5, 7, 8, 9, 10}
. However, I want to insert an element so that the array becomes {5, 6, 7, 8, 9}
inserting 6
between 5
and 7
, moving 10
out and shifting 9
to the right.
How do I use arrays and for loops to solve this problem?
Upvotes: 3
Views: 54
Reputation: 103893
arrays are extremely low-level constructs that do not have methods that do this for you. ArrayList
does which should be used for such a job.
If, as purely an academic exercise which should never make it to production, you are intrigued as to how the authors of ArrayList make such a thing:
By.. just.. doing it.
Break down the steps and perform them all.
Starting state: [5, 7, 8, 9, 10]
Desired state: [5, 6, 7, 8, 9 ]
In other words, We need to copy 7/8/9 into new positions to make room. Once that is done, we can write the 6.
int[] in = {5, 7, 8, 9, 10};
// Copy starting from index 1 (second number)
// Copy into the same array, at index 2.
// ... and copy 3 numbers.
System.arraycopy(in, 1, in, 2, 3);
System.out.println(Arrays.toString(in));
// Prints: [5, 7, 7, 8, 9].
in[1] = 6;
System.out.println(Arrays.toString(in));
// Prints: [5, 6, 7, 8, 9].
Upvotes: 2