当前位置: 首页 > news >正文

Useage of Generic in Java

the usage of generic in class

// 
public class A <T>{     //without specify a parent class or implemented interface as the super bound for generic type
    T n;
    public void printstr(){
        System.out.println(n);
    }
    A(T a){
        this.n=a;
        System.out.println("A构建成功 "+a.getClass().getSimpleName());
    }
    public static void main(String[] args) {
        A<String> a=new A("hellow world");
    }
}
//specify Class A or implemented interface as the super bound for gerceric type T
public class B <T extends A>{   //”T extends B & C“ you can use & operator to specify multiple interface when bounding a generic type parameter. If there is a parent,ther parent class must put the first.
    T a;
    B(T a){
        this.a = a;
    }
    public void A_method(){
        a.printstr();
    }
    public static void main(String[] args) {
        B b=new B(new A("testb"));
        b.A_method();
    }
}

the usage of generic in method

public class Main {
    public static <T> void Obj_Print(T a){   //in gerneric method,the type declaration must be placed before the return type
        System.out.println(a.getClass());
    }
    public static void main(String[] args) {   
        Obj_Print("Hello World");
    }
}

now ,suppose i need create a function,which’s method is printing the elements’type of list,weather the list contains any type;

maybe you think of the fowlling methods,however it's fault

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("A");
       listPrint(list);
    }
    public static <T> void listPrint(List<Objects> list){
        System.out.println(list.getClass());
    }

the reason of the erro?

Although Object is super class of String,but List<Objects> isn’t the super class of List<String>

the proper way: use wild card

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("A");
       listPrint(list);
    }
    public static <T> void listPrint(List<?> list){
        System.out.println(list.getClass());
    }

finally: the opposite usage of “extends” is “super”; specify the subclass or implemented interface as low bound for generic

相关文章:

  • 数据结构——树与二叉树
  • Java 大视界 -- Java 大数据在智能政务舆情引导与公共危机管理中的应用(138)
  • 【电源】斩波电路
  • 使用Ollama本地部署DeepSeek
  • 中国在 AI 上超越美国,需要另辟蹊径
  • LeetCode hot 100—最小栈
  • Android第三次面试总结(网络篇)
  • 线性回归与投影的关系
  • SpringBoot + Mybatis Plus 整合 Redis
  • 文本检测-文本内容审核-文本过滤接口如何用PHP调用?
  • 大华HTTP协议在智联视频超融合平台中的接入方法
  • 每日一题---翻转二叉树
  • 软件项目设计思维:从用户痛点到数字世界的优雅解构
  • 黑马商城完成随笔
  • 文心大模型4.5及X1重磅上线,真实测评
  • svg画图
  • MySQL复合查询
  • RocketMQ学习
  • 二次型 → 矩阵的正定性 → 特征值
  • 详解软件设计原则
  • 中国巴西关于乌克兰危机的联合声明
  • 反犹、资金与抗议:特朗普的施压如何撕裂美国大学?|907编辑部
  • 乌方:泽连斯基只接受与普京会谈,拒见其他俄代表
  • 为惩戒“工贼”,美国编剧工会“痛下杀手”
  • 从普通人经历中发现历史,王笛解读《线索与痕迹》
  • 国产水陆两栖大飞机AG600批产首架机完成总装下线