欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

泛型 -- 泛型类

程序员文章站 2024-03-15 10:56:53
...
/**
 * 简单的泛型类定义:
 *      类名后加<泛型>(E表示集合的元素类型,K,V分别表示key和value,T(U,S)表示任意类型)
 */
public class Pair<T> {
    private T first;
    private T second;

    public Pair() {
        first = null;
        second = null;
    }
    public Pair(T first,T second){
        this.first = first;
        this.second = second;
    }

    public T getFirst() {
        return first;
    }

    public void setFirst(T first) {
        this.first = first;
    }

    public T getSecond() {
        return second;
    }

    public void setSecond(T second) {
        this.second = second;
    }
}


public class ArrayAlg {
    public static Pair<String> minmax(String[] a){
        if(a == null || a.length == 0){
            return null;
        }
        String min = a[0];
        String max = a[0];
        for(int i=0;i<a.length;i++){
            if(min.compareTo(a[i])>0){
                min = a[i];
            }
            if(max.compareTo(a[i])<0){
                max = a[i];
            }
        }
        return new Pair<String>(min,max);
    }
}

public class Test {
    public static void main(String[] args) {
        String[] words = {"Marry","had","little","a","lamb"};
        Pair<String> str = ArrayAlg.minmax(words);
        System.out.println("min ="+str.getFirst());
        System.out.println("max ="+str.getSecond());
    }
}


相关标签: java 泛型