java泛型

2019-08-26 06:26:32来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:进程和线程,并发和并行,同步和异步,高并发和多线程,理一理概

下一篇:Spring入门(十):Spring AOP使用讲解