Java泛型编程

64 篇文章 1 订阅


    1.所谓泛型(Grenerics)是指在对象建立的时候不指定具体的类型而是在申明和实例化对象的时候指定具体的类型;
    2.需要泛型最重的因素有两点:第一,包容各种类型的变化,第二,框架基于泛型能够“容易”,例如hadoop和Spark都大量使用了泛型
    3.泛型类:
 

     public class JavaGenerics {
        public static void main(String[] args){
            Empty<String> empty = null;
            empty = new Empty<String>("Spark");
            System.out.println("Content :"+empty.getItem());

        }
    }   

    class Empty<T>{
        private  T item;
        
        public T getItem() {
            return item;
        }

        public void setItem(T item) {
            this.item = item;
        }

        public Empty(T item) {
            this.item = item;
        }
    }

   

    4.“?”表示任意的类型
      

 private static void log(Empty<? extends String, ? extends Number> empty) {
        System.out.println(empty.getKey() +" "+empty.getValue());
    }


    5.泛型的上限:限定具体泛型的范围,使用类型的extends关键字来限定
    

class Empty<K extends String,V extends Number> {
    private K key;
    private V value;

    public K getKey() {
        return key;
    }

    public void setKey(K key) {
        this.key = key;
    }

    public V getValue() {
        return value;
    }

    public void setValue(V value) {
        this.value = value;
    }

    public Empty(K key, V value) {
        this.key = key;
        this.value = value;
    }
}


    6.泛型下限:限定具体泛型向下的范围,使用super关键字来限定;
    7.泛型接口:

public class javaGenerics {
    public static void main(String[] args){
        ITNews<String> itNews = new ITNews<>("Spark is Faster");
    }

 interface News<T>{

    public T getContent();
 }

 class  ITNews<T> implements News<T>{
    private T content;

     public ITNews(T spark_is_faster) {
         this.content = spark_is_faster;
     }

     public void setContent(T content) {
         this.content = content;
     }

     @Override
     public T getContent(){
        return content;
    }
 }
public class JavaGenerics {
    public static void main(String[] args){
      
        Integer[] data = {1,2,3,4,5,6,7};
        arrayGenerics(data);

    }

    private static <T> void arrayGenerics(T[] data) {
        for (T item : data){
            System.out.println(item);
        }
    }

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值