Home >Java >javaTutorial >Detailed explanation of cases using generic methods in java

Detailed explanation of cases using generic methods in java

php是最好的语言
php是最好的语言Original
2018-08-04 13:37:161638browse

I tried to write a sorting generic method, but it turned out that I needed to use compareTo. But when the compiler was compiling, it was found that it could not be used.

Later, when I was flipping through the book, I discovered that 8742468051c85b06f0a0af9e3e506b5c needs to be written as 95ef526670d9d33fc249c9bff4dd5789 in order to use the compareTo function!

For generic construction arrays, new8742468051c85b06f0a0af9e3e506b5c cannot be used to construct it, but only

str=(T[])Array.newInstance(a.getClass().getComponentType(),a.length);进行构造

. For initialization of generic classes, use

sorts<String>sort1=new sorts<>(str);

for generics. type, if you want to use compareTo, you cannot use the int class, you have to use the Integer class

Integer[] number=new Integer[lo];

Take quick sort as an example, the source code is as follows!

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;


class sorts
{
    T[] str;
    sorts(T[]a){
     str=(T[])Array.newInstance(a.getClass().getComponentType(),a.length);
    for(int i=0;i=0)lo++;
            if(losort2=new sorts<>(number);
        sort2.quick_sort(0,number.length);
//       Arrays.sort(number);
       for(int i=0;i

Related articles:

About generic classes, generic methods, and generic interfaces in java

Generics in Java Type method

The above is the detailed content of Detailed explanation of cases using generic methods in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn