如何在Java中實現(xiàn)數(shù)組元素倒序?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
平房ssl適用于網(wǎng)站、小程序/APP、API接口等需要進行數(shù)據(jù)傳輸應(yīng)用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)公司的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18980820575(備注:SSL證書合作)期待與您的合作!
直接數(shù)組元素對換
@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存入和取出的順序是一樣的,可以利用這里特性暫時存儲數(shù)組元素.
@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)); Listlist = 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'}; // 應(yīng)該定義或轉(zhuǎn)換成對應(yīng)的引用類型: // 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); } } /** * 記錄操作執(zhí)行總時間. * * @paramthe generic type * @param clazz the clazz * @param methodName the method name */ public void recordTime(Class 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"); }
測試結(jié)果:
使用Collections和Arrays工具類: 12 ms
使用ArrayList: 7 ms
直接數(shù)組元素對換: 4 ms
當數(shù)據(jù)量越來越大時,使用ArrayList的方式會變得很慢.
直接使用數(shù)組元素對換,總是最快完成.
看完上述內(nèi)容,你們掌握如何在Java中實現(xiàn)數(shù)組元素倒序的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!