Java custom generic interview questions: receive any array to reverse, java custom
You can only operate on a certain type for reversal without using the generic type.
The Code is as follows:
package com.swift.fanxing;import org.junit.Test;public class RenyiReverse { @Test public void test() { int arr[]=new int[] {1,10,6,9,2}; reverse(arr); } public void reverse(int[] arr) { for(int i=0;i<arr.length/2;i++) { int temp=arr[i]; arr[i]=arr[arr.length-1-i]; arr[arr.length-1-i]=temp; } for(int x:arr) { System.out.println(x); } }}
In addition to applications on the set iterator, the generic function can also receive variables or arrays of any type of classes.
Package com. swift. fanxing; import org. junit. test; public class RenyiReverse {@ Test public void test () {Integer arr [] = new Integer [] {1, 10, 6, 9, 2 }; // here, you cannot use int to replace Integer String arr2 [] = new String [] {"aa", "bb", "cc", "dd", "ee "}; reverse (arr); reverse (arr2);} public <T> void reverse (T [] arr) {for (int I = 0; I <arr. length/2; I ++) {T temp = arr [I]; arr [I] = arr [arr. length-1-i]; arr [arr. length-1-i] = temp;} for (T x: arr) {System. out. println (x );}}}
Non-static declaration is in place, static declaration is in place, and class declaration is global. For multi-generic declaration, <T, J, K>