-3

Is it possible to re-arrange indexes on arrays? Lets say String myArray [] = {"a","b","c","d"} and rearrange the indexes to acbd as the output, sorry for the noob question.

enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
Ryan Arellano
  • 79
  • 1
  • 9

3 Answers3

3

you need a temp variable

temp =myarray[1]
myarray[1] = myarray[2]
myarray[2] = temp
Justin
  • 1,356
  • 2
  • 9
  • 16
1

Use a temporary variable.

String temp = myarray[1];
myarray[1] = myarray[2];
myarray[2] = temp;

If memory is a big issue you can set it to null afterwards (temp = null;), but this usually isn't a problem.

LemenDrop
  • 160
  • 1
  • 3
  • 11
0

If you want to reorder elements in Java it's best to do it with Lists. For example you can write

List<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c", "d", "e"));
Collections.rotate(list.subList(1, 4), 1);
System.out.println("" + list);

and the output is [a, d, b, c, e]. Doing this kind of thing with arrays is much harder.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116