Java数组元素倒序的三种⽅式(⼩结)将数组元素反转有多种实现⽅式,这⾥介绍常见的三种.
直接数组元素对换
@Test
public void testReverseSelf() throws Exception {
System.out.println("use ReverseSelf");
String[] strings = { "ramer", "jelly", "bean", "cake" };
System.out.println("\t" + String(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" + String(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" + String(strings));
List<String> list = new ArrayList<>(strings.length);
for (int i = strings.length - 1; i >= 0; i--) {
list.add(strings[i]);
}
strings = Array(strings);
System.out.println("\t" + String(strings));
}
使⽤Collections和Arrays⼯具类
@Test
public void testCollectionsReverse() throws Exception {
System.out.println("verse() method");
String[] strings = { "ramer", "jelly", "bean", "cake" };
System.out.println("\t" + String(strings));
/
/ 这种⽅式仅针对引⽤类型,对于基本类型如:
// char[] cs = {'a','b','c','g','d'};
// 应该定义或转换成对应的引⽤类型:
// Character[] cs = {'a','b','c','g','d'};
System.out.println("\t" + String(strings));
}
速度测试:
@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 = DeclaredMethods();
for (Method method : declaredMethods) {
java valueofString name = Name();
if (name.equals(methodName)) {
try {
method.wInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
}
long end = System.currentTimeMillis();
System.out.println("end: " + end);
System.out.println("duration: " + (end - start) + " ms");
}
测试结果:
使⽤Collections和Arrays⼯具类: 12 ms
使⽤ArrayList: 7 ms
直接数组元素对换: 4 ms
当数据量越来越⼤时,使⽤ArrayList的⽅式会变得很慢.
直接使⽤数组元素对换,总是最快完成.
总结: 使⽤Collections和Arrays⼯具类反转数组元素更简单,但是在原数组上操作时速度更快,并且占⽤最少的内存.以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。