java泛型的说明及使用

  1. 泛型技术产生的背景

    1. 在泛型出来之前,程序员是通过object对象来存储任意值的集合,该方法在使用时,必须知道存储的类型,否组容易引起classcastexcption异常
  2. 泛型操作的实现

    1. package com.iflytek.request.genericity;
      
      public class Genericity {
      
      
          public void point_Integer() {
              Point<Integer> point = new Point();
              point.setX(1);
              point.setY(2);
          }
      
          public void point_String() {
              Point<String> point = new Point();
              point.setX("1");
              point.setY("2");
          }
      
          public void name_String() {
              Name<String,Integer> name = new Name();
              name.setF(10);
              name.setX("name");
          }
      
      
          public class Name<T,F> {
      
              public T getX() {
                  return x;
              }
      
              public void setX(T x) {
                  this.x = x;
              }
      
              public F getF() {
                  return f;
              }
      
              public void setF(F f) {
                  this.f = f;
              }
      
              private T x;
              private F f;
          }
      
          public class Point<T> {
      
              private T x;
      
              public T getX() {
                  return x;
              }
      
              public void setX(T x) {
                  this.x = x;
              }
      
              public T getY() {
                  return y;
              }
      
              public void setY(T y) {
                  this.y = y;
              }
      
              private T y;
          }
      
      }
      

       

  3. 泛型接口定义及实现

    1. public interface IGenericity<T>{
      
          public void setValue(T t);
      
      }
      
      public class IMainGenericity implements IGenericity<Float> {
          @Override
          public void setValue(Float s) {
      
          }
      }
      
      public class Genericity {
      
          public void Imain() {
              IMainGenericity iGenericity = new IMainGenericity();
              iGenericity.setValue((float) 1.0);
          }
      }

       

  4. 通配符的使用

    1. 泛型类名<? extends T> 或 泛型类名<? super T> 或 泛型类名<?>

      ? extends T:表示T或T的子类

      ? super T:表示T或T的父类

      ?:表示可以是任意类型

    2. 通配符主要了解向上向下的转型,只可获取,不可设置

 

备注:不同情境下使用字符的用意

E:Element,常在java的collection里,List<E>,set<E>,Iterator<E>

K,V:key,value,键值对map中使用

N:Number,数字

T:Type,类型如String,Integer,Float等等

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值