Basics Of Java Generics
这里是这篇文章的随笔记录:https://www.baeldung.com/java-generics , 内容非常基础,可参考原文。如果想了解关于泛型更深入的,可以参考这篇:http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html (非常详细)
1. The Basics:
1.1 Generic Methods
demo1:
public <T> List<T> fromArrayToList(T[] a) { return Arrays.stream(a).collect(Collectors.toList()); }
The <T> in the method signature implies that the method will be dealing with generic type T. This is needed even if the method is returning void.
As mentioned, the method can deal with more than one generic type. Where this is the case, we must add all generic types to the method signature.
Here is how we would modify the above method to deal with type T and type G:
public static <T, G> List<G> fromArrayToList(T[] a, Function<T, G> mapperFunction) { return Arrays.stream(a) .map(mapperFunction) .collect(Collectors.toList()); }
@Test public void givenArrayOfIntegers_thanListOfStringReturnedOK() { Integer[] intArray = {1, 2, 3, 4, 5}; List<String> stringList = Generics.fromArrayToList(intArray, Object::toString); assertThat(stringList, hasItems("1", "2", "3", "4", "5")); }
1.2 Bounded Generics
public <T extends Number> List<T> fromArrayToList(T[] a) { ... }
1.3 wildcard with Generics
public static void paintAllBuildings(List<Building> buildings) { buildings.forEach(Building::paint); }
public static void paintAllBuildings(List<? extends Building> buildings) { ... }
2. Generic Class
// Java program to show multiple // type parameters in Java Generics // We use < > to specify Parameter type class Test<T, U> { T obj1; // An object of type T U obj2; // An object of type U // constructor Test(T obj1, U obj2) { this.obj1 = obj1; this.obj2 = obj2; } // To print objects of T and U public void print() { System.out.println(obj1); System.out.println(obj2); } } // Driver class to test above class Main { public static void main (String[] args) { Test <String, Integer> obj = new Test<String, Integer>("GfG", 15); obj.print(); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律