Java custom generic interview questions: receive any array to reverse, java custom

Source: Internet
Author: User

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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.