Java数组(2):数组与泛型
2024-08-30 18:51:10
通常,数组与泛型不能很好的结合,你不能实例化具有参数化类型的数组。擦除会移除参数类型信息,而数组必须知道它们所持有的确切类型。但是我们可以参数化数组本身。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List; class ClassParameter<T> {
public T[] f(T[] arg) {
return arg;
}
} class MethodParameter {
public static <T> T[] f(T[] arg) {
return arg;
}
} public class ParameterizedArrayType {
public static void main(String[] args) {
// List<String>[] ls = new List<String>[5]; // Compile ERROR: 不能实例化具有参数化类型的数组
List<String>[] ls = new List[5]; // 这样可以
ls[0] = new ArrayList<>();
// ls[1] = new ArrayList<Integer>(); // Compile ERROR: 类型不匹配
ls[2] = new LinkedList<>();
// 但是我们可以参数化数组本身。
Integer[] ints = {1, 2, 3, 4, 5};
Double[] doubles = {1.1, 2.2, 3.3, 4.4, 5.5};
Integer[] ints2 = new ClassParameter<Integer>().f(ints);
Double[] doubles2 = new ClassParameter<Double>().f(doubles);
System.out.println(Arrays.toString(ints2)); // [1, 2, 3, 4, 5]
System.out.println(Arrays.toString(doubles2)); // [1.1, 2.2, 3.3, 4.4, 5.5]
ints2 = MethodParameter.f(ints);
doubles2 = MethodParameter.f(doubles);
System.out.println(Arrays.toString(ints2)); // [1, 2, 3, 4, 5]
System.out.println(Arrays.toString(doubles2)); // [1.1, 2.2, 3.3, 4.4, 5.5]
}
}
最新文章
- .NET中AOP方便之神SheepAspect
- httphandler和httpmodule的区别
- koala不支持中文的解决办法(问题出现在使用中文字体时报错)
- 【NOI2011】道路修建 BFS
- json在php中的使用之如何转换json为数组
- mysql 操作突然断网,MySQL: “lock wait timeout exceeded”
- mysql中出现的Data truncated for column
- Implement Custom Cache Dependencies in ASP.NET 1.x
- 三个流行MySQL分支的对比
- Swift UI学习UITableView and protocol use
- SpringMVC @ResponseStatus 的用法
- python unicode 转中文 遇到的问题 爬去网页中遇到编码的问题
- JavaScript ES6 Arrow Functions(箭头函数)
- HtmlUnit入门二
- Ubuntu学习之路
- 6个顶级Python NLP库的比较!
- SQL Server数据库(时间戳timestamp)类型
- Java学习——使用final修饰符
- 关于PLC高速计数器使用
- Codeforces 235E. Number Challenge DP
热门文章
- Eclipse创建Servers没有Apache选项
- mysql基础_操作数据库以及表
- 洛谷P1080 国王游戏【大数】【贪心】
- Codeforces Round #589 (Div. 2) C - Primes and Multiplication(数学, 质数)
- Appium Inspector
- Microsoft.Practices.Unity使用配置文件总是报错The type name or alias could not be resolved.
- CaoHaha's staff (HDU 6154)(2017中国大学生程序设计竞赛 - 网络选拔赛)
- [bat]只更新svn部分文件夹
- [JZOJ6345]:ZYB建围墙(数学+构造)
- 7.RabbitMQ--消息确认机制(confirm)