Home > Java > javaTutorial > body text

Detailed explanation of cases using generic methods in java

php是最好的语言
Release: 2018-08-04 13:37:16
Original
1616 people have browsed it

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 needs to be written as in order to use the compareTo function!

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

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

. For initialization of generic classes, use

sorts<String>sort1=new sorts<>(str);
Copy after login

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];
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template