通常,数组与泛型不能很好的结合,你不能实例化具有参数化类型的数组。擦除会移除参数类型信息,而数组必须知道它们所持有的确切类型。但是我们可以参数化数组本身。

 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]
}
}

最新文章

  1. .NET中AOP方便之神SheepAspect
  2. httphandler和httpmodule的区别
  3. koala不支持中文的解决办法(问题出现在使用中文字体时报错)
  4. 【NOI2011】道路修建 BFS
  5. json在php中的使用之如何转换json为数组
  6. mysql 操作突然断网,MySQL: “lock wait timeout exceeded”
  7. mysql中出现的Data truncated for column
  8. Implement Custom Cache Dependencies in ASP.NET 1.x
  9. 三个流行MySQL分支的对比
  10. Swift UI学习UITableView and protocol use
  11. SpringMVC @ResponseStatus 的用法
  12. python unicode 转中文 遇到的问题 爬去网页中遇到编码的问题
  13. JavaScript ES6 Arrow Functions(箭头函数)
  14. HtmlUnit入门二
  15. Ubuntu学习之路
  16. 6个顶级Python NLP库的比较!
  17. SQL Server数据库(时间戳timestamp)类型
  18. Java学习——使用final修饰符
  19. 关于PLC高速计数器使用
  20. Codeforces 235E. Number Challenge DP

热门文章

  1. Eclipse创建Servers没有Apache选项
  2. mysql基础_操作数据库以及表
  3. 洛谷P1080 国王游戏【大数】【贪心】
  4. Codeforces Round #589 (Div. 2) C - Primes and Multiplication(数学, 质数)
  5. Appium Inspector
  6. Microsoft.Practices.Unity使用配置文件总是报错The type name or alias could not be resolved.
  7. CaoHaha's staff (HDU 6154)(2017中国大学生程序设计竞赛 - 网络选拔赛)
  8. [bat]只更新svn部分文件夹
  9. [JZOJ6345]:ZYB建围墙(数学+构造)
  10. 7.RabbitMQ--消息确认机制(confirm)