# Thread: Problem with shifting array elements

1. Member
Join Date
Feb 2011
Posts
8
Rep Power
0

## Problem with shifting array elements

Hi,

I need help in arrays.

Let's say i have array that contains DD,GG and JJ.

arr="DD","GG","JJ"

if i want to insert FF in between DD and GG, i would need to shift GG and JJ one space back to have this final array.

arr="DD","FF","GG","JJ"

I have written this code but i am not sure why the final results become this way.

arr="DD","FF","JJ","JJ"

Java Code:
```  for (int i = arr.length +1; i > 1; i--) {
arr[i] = arr[i-1];
}```

2. Add a print statement in there that specifies what element you're moving to which index and what the total array looks like each iteration, and you'll see what's going on.

3. Member
Join Date
Feb 2011
Posts
8
Rep Power
0
Java Code:
```for (int i = arr.length +1; i > 1; i--) {
arr[i] = arr[i-1];
System.out.println(arr[i]);
System.out.println(arr[i-1]);
}```
As in this way?

4. Senior Member
Join Date
Mar 2010
Posts
952
Rep Power
8
Originally Posted by holy.water
Java Code:
```for (int i = arr.length +1; i > 1; i--) {
arr[i] = arr[i-1];
System.out.println(arr[i]);
System.out.println(arr[i-1]);
}```
As in this way?
More like this:
Java Code:
```        for (int i = arr.length + 1; i > 1; i--) {
System.out.println("Moving " + arr[i-1] + " to index " + i);
arr[i] = arr[i-1];
System.out.print("Array is now: " + arr[0]);
for (int j = 1; j < arr.length; j++) {
System.out.print(", " + arr[j]);
}
System.out.println();
}```
-Gary-

5. Senior Member
Join Date
Feb 2011
Posts
118
Rep Power
0
No, no, no--you do NOT want to manipulate arrays directly like this. Use a java.util.ArrayList instead. To wit:

Java Code:
```List<String> list = new ArrayList<String>();

// now add "HH" at the appropriate index. All other elements will shift as needed.

// need it to be a regular array again?
String[] arr = list.toArray();```
BTW, if you don't like the way that ArrayList is populated, you can always do a quick & dirty

Java Code:
```String[] arr = new String[] { "DD", "GG", "JJ" }
List<String> list = new ArrayList<String>(Arrays.asList(arr));```
(Why not just List<String> list = Arrays.asList(arr)? Because Arrays.asList() returns a non-modifiable list.)

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•