Java泛型小随笔

今天随便写写,大家都比较熟悉的基础知识(泛型),理论知识就不在这里细说了,请自行百度,直接上代码示例比较值观。

1. 泛型-类 使用

创建一个Entity实体类,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com;
 
public class SzlDemo<T> {
    private T uName;
    private T uPwd;
    private T uAge;
 
    public SzlDemo() {
    }
 
    public SzlDemo(T uName, T uPwd, T uAge) {
        this.uName = uName;
        this.uPwd = uPwd;
        this.uAge = uAge;
    }
 
    public T getuName() {
        return uName;
    }
    public void setuName(T uName) {
        this.uName = uName;
    }
    public T getuPwd() {
        return uPwd;
    }
    public void setuPwd(T uPwd) {
        this.uPwd = uPwd;
    }
    public T getuAge() {
        return uAge;
    }
    public void setuAge(T uAge) {
        this.uAge = uAge;
    }
}

main函数测试

1
2
3
4
5
6
7
8
9
10
package com;
 
public class Test1 {
 
    public static void main(String[] args) {
        // 泛型类 使用
        SzlDemo<String> demo = new SzlDemo<String>("sss", "bbb", "16");
        System.out.println(demo.getuName() + " : " + demo.getuAge());
    }
}

 

2. 泛型-接口 使用

创建接口定义

1
2
3
4
5
package com.api;
 
public interface SzlDemoApi<T> {
    T getMsg(T msg);
}

 接口实现类

1
2
3
4
5
6
7
8
9
10
11
12
package com.api.impl;
 
import com.api.SzlDemoApi;
 
public class SzlDemoApiImpl implements SzlDemoApi<String> {
 
    @Override
    public String getMsg(String msg) {
        return "这是泛型案例,返回信息为:" + msg;
    }
     
}

 main函数测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com;
 
import com.api.SzlDemoApi;
import com.api.impl.SzlDemoApiImpl;
 
public class Test1 {
 
    public static void main(String[] args) {
        // 泛型接口 使用
        SzlDemoApi<String> szlDemoApi = new SzlDemoApiImpl();
        String resutlMsg = szlDemoApi.getMsg("haha, 冲啊!!!");
        System.out.println(resutlMsg);
    }
}

 

3. 泛型-方法 使用

创建一个类,定义一个数字加法的方法

1
2
3
4
5
6
7
8
package com;
 
public class SzlDemo2 {
 
    public static <T extends Number> Double calPlus(T a, T b) {
        return a.doubleValue() + b.doubleValue();
    }
}

  main函数测试

1
2
3
4
5
6
7
8
9
10
11
12
13
package com;
 
import com.api.SzlDemoApi;
import com.api.impl.SzlDemoApiImpl;
 
public class Test1 {
 
    public static void main(String[] args) {
        // 泛型方法 使用
        int t1 = 3, t2 = 6;
        System.out.println("Integer类型相加为:" + SzlDemo2.calPlus(t1, t2).intValue());
    }
}

 

posted @   JimmyShan  阅读(184)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示