首页 > 编程语言 > 详细

java泛型

时间:2019-08-22 23:48:19      阅读:162      评论:0      收藏:0      [点我收藏+]

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

 

java泛型

原文:https://www.cnblogs.com/sunzhongyu008/p/11397215.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!