Three ways to reverse the order of Java array elements (summary)

There are many ways to reverse array elements. Here are three common ways

Direct array element exchange

@Test
public void testReverseSelf() throws Exception {
  System.out.println("use ReverseSelf");

  String[] strings = { "ramer","jelly","bean","cake" };
  System.out.println("\t" + Arrays.toString(strings));
  for (int start = 0,end = strings.length - 1; start < end; start++,end--) {
    String temp = strings[end];
    strings[end] = strings[start];
    strings[start] = temp;
  }
  System.out.println("\t" + Arrays.toString(strings));
}

Use ArrayList: ArrayList is stored and retrieved in the same order. You can use this feature to temporarily store array elements

@Test
public void testArrayList() throws Exception {
  System.out.println("use ArrayList method");

  String[] strings = { "ramer","cake" };
  System.out.println("\t" + Arrays.toString(strings));
  List<String> list = new ArrayList<>(strings.length);
  for (int i = strings.length - 1; i >= 0; i--) {
    list.add(strings[i]);
  }
  strings = list.toArray(strings);
  System.out.println("\t" + Arrays.toString(strings));
}

Using collections and arrays utility classes

@Test
public void testCollectionsReverse() throws Exception {
  System.out.println("use Collections.reverse() method");

  String[] strings = { "ramer","cake" };
  System.out.println("\t" + Arrays.toString(strings));
  // 这种方式仅针对引用类型,对于基本类型如:
  // char[] cs = {'a','b','c','g','d'};
  // 应该定义或转换成对应的引用类型:
  // Character[] cs = {'a','d'};
  Collections.reverse(Arrays.asList(strings));
  System.out.println("\t" + Arrays.toString(strings));
}

Speed test:

@Test
public void testTimeDuration() throws Exception {
  recordTime(ArrayReverse.class,"testCollectionsReverse");
  recordTime(ArrayReverse.class,"testArrayList");
  recordTime(ArrayReverse.class,"testReverseSelf");
}

private static String[] strings = new String[1000000];
{
  for (int i = 0; i < 1000000; i++) {
    strings[i] = String.valueOf(i);
  }
}
/**
 * 记录操作执行总时间.
 *
 * @param <T> the generic type
 * @param clazz the clazz
 * @param methodName the method name
 */
public <T> void recordTime(Class<T> clazz,String methodName) {
  long start = System.currentTimeMillis();
  System.out.println("start: " + start);

  Method[] declaredMethods = clazz.getDeclaredMethods();
  for (Method method : declaredMethods) {
    String name = method.getName();
    if (name.equals(methodName)) {
      try {
        method.invoke(clazz.newInstance());
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
  long end = System.currentTimeMillis();
  System.out.println("end: " + end);
  System.out.println("duration: " + (end - start) + " ms");
}

Test results:

Summary: it is easier to invert array elements using collections and arrays tool classes, but it is faster and takes up the least memory when operating on the original array

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>