数组元素倒序
将数组元素反转有多种实现方式,这里介绍常见的三种.
原文链接:https://blog.csdn.net/u011699931/article/details/52554787
直接数组元素对换
@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));
}
使用ArrayList: ArrayList存入和取出的顺序是一样的,可以利用这里特性暂时存储数组元素.
@Test
public void testArrayList() throws Exception {
System.out.println("use ArrayList method");
String[] strings = { "ramer", "jelly", "bean", "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));
}
使用Collections和Arrays工具类
@Test
public void testCollectionsReverse() throws Exception {
System.out.println("use Collections.reverse() method");
String[] strings = { "ramer", "jelly", "bean", "cake" };
System.out.println("\t" + Arrays.toString(strings));
/* 这种方式仅针对引用类型,对于基本类型如:
char[] cs = {'a','b','c','g','d'};
应该定义或转换成对应的引用类型:
Character[] cs = {'a','b','c','g','d'};*/
Collections.reverse(Arrays.asList(strings));
System.out.println("\t" + Arrays.toString(strings));
}