Results 1 to 5 of 5
- 02-25-2011, 06:14 PM #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"
Pls advise. Thank You.Java Code:for (int i = arr.length +1; i > 1; i--) { arr[i] = arr[i-1]; }
- 02-25-2011, 06:17 PM #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.
How to Ask Questions the Smart Way
Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!
- 02-25-2011, 06:25 PM #3
Member
- Join Date
- Feb 2011
- Posts
- 8
- Rep Power
- 0
As in this way?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]); }
- 02-25-2011, 07:08 PM #4
Senior Member
- Join Date
- Mar 2010
- Posts
- 953
- Rep Power
- 4
More like this:
-Gary-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(); }
- 02-25-2011, 08:56 PM #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:
BTW, if you don't like the way that ArrayList is populated, you can always do a quick & dirtyJava 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();
(Why not just List<String> list = Arrays.asList(arr)? Because Arrays.asList() returns a non-modifiable list.)Java Code:String[] arr = new String[] { "DD", "GG", "JJ" } List<String> list = new ArrayList<String>(Arrays.asList(arr));
Similar Threads
-
Q about shifting data in an array
By alihht in forum New To JavaReplies: 7Last Post: 02-03-2010, 06:17 AM -
Shifting characters in array
By Mayur in forum New To JavaReplies: 2Last Post: 04-24-2009, 10:19 PM -
[SOLVED] Shifting an array
By VeasMKII in forum New To JavaReplies: 2Last Post: 02-04-2009, 06:18 PM -
PROBLEM - calculating with array elements
By ella in forum New To JavaReplies: 13Last Post: 12-04-2008, 12:36 AM -
Help with array of elements
By zoe in forum New To JavaReplies: 1Last Post: 07-24-2007, 05:33 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks