# Problem with shifting array elements

• 02-25-2011, 07:14 PM
holy.water
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"

Code:

```  for (int i = arr.length +1; i > 1; i--) {         arr[i] = arr[i-1];       }```
Pls advise. Thank You.
• 02-25-2011, 07:17 PM
KevinWorkman
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.
• 02-25-2011, 07:25 PM
holy.water
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?
• 02-25-2011, 08:08 PM
gcalvin
Quote:

Originally Posted by holy.water
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:
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-
• 02-25-2011, 09:56 PM
NRitH
No, no, no--you do NOT want to manipulate arrays directly like this. Use a java.util.ArrayList instead. To wit:

Code:

```List<String> list = new ArrayList<String>(); list.add("DD"); list.add("GG"); list.add("JJ"); // now add "HH" at the appropriate index. All other elements will shift as needed. list.add(1, "HH"); // 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

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