• 11-泛型


    一:

    注意:数据类型的安全性问题可以理解为避免了数据类型转换错误。

     1 package com.example;
     2 //?是通配符,object是任意类型,不写类型
     3 class A<T>{
     4     private T age;
     5     private T name;
     6 
     7     public T getAge() {
     8         return age;
     9     }
    10 
    11     public void setAge(T age) {
    12         this.age = age;
    13     }
    14 
    15     public T getName() {
    16         return name;
    17     }
    18 
    19     public void setName(T name) {
    20         this.name = name;
    21     }
    22 }
    23 public class MyClass {
    24     public static void main(String[] args){
    25         A<String> a = new A<String>();
    26         a.setAge("100");
    27         a.setName("hello");
    28         System.out.println("name is :"+ a.getName() + ",age is :"+ a.getAge());
    29     }
    30 }
    View Code

    二:通配符

    三:泛型接口

     1 package com.example;
     2 interface a<T>{
     3     public abstract void say(T name);
     4 }
     5 
     6 class People implements a<String>{
     7 
     8     int b;
     9 
    10     public int getB() {
    11         return b;
    12     }
    13 
    14     public void setB(int b) {
    15         this.b = b;
    16     }
    17 
    18     @Override
    19     public void say(String name) {
    20         System.out.print(this.getB()+name);
    21 
    22     }
    23 }
    24 
    25 public class MyClass {
    26     public static void main(String[] args){
    27         People p = new People();
    28         p.b = 10;
    29         p.say("hello");
    30     }
    31 }
    View Code

    四:泛型方法

     1 package com.example;
     2 class A {
     3     public <T>T tell(T t){
     4         System.out.println(t);
     5         return t;
     6     };
     7 }
     8 public class MyClass {
     9     public static void main(String[] args){
    10         A a = new A();
    11         a.tell("hello");
    12         a.tell(12);
    13     }
    14 }
    View Code

    五:泛型数组

     1 package com.example;
     2 
     3 public class MyClass {
     4     public static void main(String[] args){
     5         String arr[] = {"i","am","zwzx"};
     6         tell(arr);
     7     }
     8     public static  <T>void tell(T arr[]){
     9         for (int i = 0 ;i <arr.length;i++){
    10             System.out.println(arr[i]);
    11         }
    12     }
    13 }
    View Code
  • 相关阅读:
    hdu 1548 升降梯
    hdu 2544 hdu 1874 poj 2387 Dijkstra 模板题
    hdu 4463 有一条边必须加上 (2012杭州区域赛K题)
    poj 1679 判断MST是不是唯一的 (次小生成树)
    poj 1751 输出MST中新加入的边
    poj 2349 求MST中第S大的权值
    HDU 4389 X mod f(x) (数位DP)
    HDU 5908 Abelian Period (暴力)
    HDU 5907 Find Q (水题)
    HDU 4514 湫湫系列故事――设计风景线 (树形DP)
  • 原文地址:https://www.cnblogs.com/BelieveFish/p/6295118.html
Copyright © 2020-2023  润新知