There are several implementations of the inverse of an array element, and here are three common types.
- Direct array Element swap
@Testpublic 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));}
- The order in which the arraylist:arraylist is deposited and taken out is the same, and you can use this feature to temporarily store the array elements.
@Testpublic 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 (stri NGS); System.out.println ("\ T" + arrays.tostring (Strings));}
- using collections and Arrays tool classes
@Test public void testcollectionsreverse () throws Exception {System.out.println ( "use Collections.reverse () method"); String[] strings = { "jelly", "Bean", "cake"}; System.out.println ( "\ T" + arrays.tostring (strings)); //This method is only for reference types, for basic types such as: //char[] cs = {' A ', ' B ', ' C ', ' G ', ' d '}; Span class= "Hljs-comment" >//should be defined or converted to the corresponding reference type: //character[] cs = {' A ', ' B ', ' C ', ' G ', ' d '}; Collections.reverse (Arrays.aslist (strings)); System.out.println ( "\ T" + arrays.tostring (Strings));
@TestPublicvoidTesttimeduration ()Throws Exception {Recordtime (Arrayreverse.class,"Testcollectionsreverse"); Recordtime (Arrayreverse.class,"Testarraylist"); Recordtime (Arrayreverse.class,"Testreverseself");}PrivateStatic string[] strings =New string[1000000]; {for (int i =0; I <1000000; i++) {Strings[i] = string.valueof (i);}}/** * Records the total time of operation execution. * *@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.currentti Memillis (); 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");}
Three ways to reverse the Java array elements