重载与泛型擦除
重载是面向对象语言重要的特性之一,判断重载可以根据参数列表的不同来决定是否两个方法是否存在重载。但返回值却不会成为判断因素之一,这是因为函数调用时并没有特征显示被调函数的返回值信息,也就无法区别被调用的是哪个函数。
泛型擦除是指任何泛型的参数变量在编译时,都会被擦除成Object类,即List<Integer>与List<String>在编译时都被擦除成List<Object>。假如存在两个方法 void function(List<Integer>),void function(List<String>),按照重载定义,这两种方法的参数列表不同,是重载的。但泛型擦除的定义又告诉我们这两种方法是完全一样的,属于重定义。以下面例子为例:
public class Clean {public void method(ArrayList<String> a) {System.out.println("call method ArrayList<String>");}public void method(ArrayList<Integer> a) {System.out.println("call method ArrayList<Integer>");}public static void main(String[] args) {}}
public class Clean {public String method(ArrayList<String> a) {System.out.println("call method ArrayList<String>");return "";}public int method(ArrayList<Integer> a) {System.out.println("call method ArrayList<Integer>");return 1;}public static void main(String[] args) {Clean clean = new Clean();clean.method(new ArrayList<Integer>());clean.method(new ArrayList<String>());}}
call method ArrayList<Integer>call method ArrayList<String>