How to embody or implement the mechanism of CPP function template in JAVA

for example, CPP writes a function to find the maximum value
Please enter the code

int max(int x,int y)
{
return (x>y)?x:y;
}

at this point, if the argument is floating-point, you need to define a function version

.
float max(float x,float y)
{
return (x>y)?x:y;
}

the contents of these functions are basically the same, but the parameters and return types are different, so there will be a lot of duplicate information in each definition. In CPP, the function template is used to solve

.
template <class T>
T max(T x, T y)
{
return (x>y)?x:y;
}

for example, I implemented a method of exchanging array elements in Java:

void swap(int[] array , int i , int j ){
    int temp = i ;
    i = j ;
    j = temp ;
}

then I found that there are not only arrays of type int, but also arrays of String and float, and the function is the same. how should I implement it? There can"t be any array, so I"ll rewrite a function with arguments to String array and float array.

how are problems like this solved in JAVA? If you implement a function similar to a function template in CPP

Mar.23,2021

Java generics learn about


take a chestnut ~

  

understand the mechanism of Java generics

Menu