java泛型

1.泛型类与泛型方法

package Generic;

import java.io.Serializable;
import java.time.LocalDate;
import Generic.ArrayAlg.Pair;

public class ArrayDemo{
    public static void main(String[] args) {
        LocalDate[] birthdays = {
            LocalDate.of(1906, 12, 9),
            LocalDate.of(1815, 12, 10),
            LocalDate.of(1903, 12, 3),
            LocalDate.of(1910, 6, 22)
        };
        Pair<LocalDate> mm = ArrayAlg.minmax(birthdays);
        System.out.println("min = " + mm.getFirst());
        System.out.println("max = " + mm.getSecond());
    }
}

class ArrayAlg{    
    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 this.first;
        }
        
        public T getSecond() {
            return this.second;
        }
        
        public void setFirst(T newValue){
            first = newValue;
        }
        
        public void setSecond(T newValue) {
            second = newValue;
        }
    }
    
    public class Interval<T extends Comparable & Serializable> implements Serializable{
        private T lower;
        private T upper;

        public Interval(T first, T second) {
            if(first.compareTo(second)<=0) {
                lower = first;
                upper = second;
            }else {
                lower = second;
                upper = first;
            }
        }
    }
    
    public static <T extends Comparable> Pair<T> minmax(T[] array) {
        if (array == null || array.length == 0) {
            return null;
        }
        
        T min = array[0];
        T max = array[0];
        for (int i = 1; i < array.length; i++) {
            if (min.compareTo(array[i]) > 0) {
                min = array[i];
            }
            if (max.compareTo(array[i]) < 0) {
                max = array[i];
            }
        }
        
//        ArrayAlg arrayAlg = new ArrayAlg();
//        return arrayAlg.new Pair<>(min, max);
        return (new ArrayAlg()).new Pair<>(min, max);//这条语句等同于上面两行
    }
}

运行结果:

min = 1815-12-10
max = 1910-06-22

 

    原文作者:逍遥天地间
    原文地址: https://www.cnblogs.com/sunzhongyu008/p/11397215.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞