如何在Java中实现数组元素倒序?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
直接数组元素对换
@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));
}
速度测试:
@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");
}
测试结果:
使用Collections和Arrays工具类: 12 ms
使用ArrayList: 7 ms
直接数组元素对换: 4 ms
当数据量越来越大时,使用ArrayList的方式会变得很慢.
直接使用数组元素对换,总是最快完成.
看完上述内容,你们掌握如何在Java中实现数组元素倒序的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。