泛型和类方法(Generics and Class Method)

package com.tyq;

public class Generics<T> {
    public static <T>void sort(T[] a){
        if(a[0] instanceof Number&&a.length>0){
           
            int k = 0;
            for(;k < a.length; k++){
                T temp = a[k];
                for(int j = k+1;j < a.length;j++){
                    if(Double.parseDouble(a[k].toString()) > Double.parseDouble(a[j].toString())){
                        a[k] = a[j];
                        a[j] = (T) temp;
                        temp = a[k];
                    }
                }
            }
        }
        return ;
    }
    public void print(T[] a){
        //sort(a);
        if(a.length>0){
            int i = 0;
            for(int j = 0;j < a.length;j++){
                System.out.println((i+1)+":"+a[j]);
                i++;
            }
        }
    }
    public void print_1(T[] a){
        sort(a);
        if(a.length>0){
            int i = 0;
            for(int j = 0;j < a.length;j++){
                System.out.println((i+1)+":"+a[j]);
                i++;
            }
        }
    }
}

package com.tyq;

public class Test {

    /**
    * @param args
    */
    public static void main(String[] args) {
        Float t[] = {new Float(5),
                new Float(2),
                new Float(9),
                new Float(47),
                new Float(565),};
        Double x[] = {new Double(7.8889),
                new Double(8.888),
                new Double(2.31),
                new Double(1.023),
                new Double(5.36),};
       
        Generics<Double> test = new Generics<Double>();//使用泛型
        Generics<Float> test_1 = new Generics<Float>();//使用泛型
        //test.sort(t);
        Generics.sort(x); //调用类方法
        test.print(x);    //调用实例方法
        System.out.println("在实例方法中调用类方法:");
        test_1.print_1(t);

    }

}


输出结果:
1:1.023
2:2.31
3:5.36
4:7.8889
5:8.888
在实例方法中调用类方法:
1:2.0
2:5.0
3:9.0
4:47.0
5:565.0

java 学习交流

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值