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的方式會變得很慢.
    直接使用數組元素對換,總是最快完成.

  • 總結: 使用Collections和Arrays工具類反轉數組元素更簡單,但是在原數組上操作時速度更快,並且占用最少的內存.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2024 CODEPRJ.COM