java 中的方法重载 - 使用列表类型
Method Overloading in java - using List Type
class Value {
public void method1(List<Integer> intList) {
}
public void method1(List<Double> doubleList) {
}
}
以上两种方法都不能使用函数重载
看起来这两种方法都将 List
作为参数。
有没有办法区分列表数据类型的参数?
这是错误信息:
Erasure of method method1(List<Integer>) is the same as another method in type Value
有没有其他方法可以在这里使用重载?
您可以使用 method1(List<Object> List)
并使用 instanceof
检查方法中的类型
您不能声明多个具有相同名称以及相同数量和类型的参数的方法,因为编译器无法区分它们。参见 oracle docs。
您可以为此使用泛型:
public void method1(List<?> list) {
}
这样的声明方式,可以查看列表的内容,做自己需要的工作:
public static void check(List<?> list) {
// check null
if (Objects.equals(null, list))
System.out.println("null");
// check empty
else if (list.isEmpty())
System.out.println("empty");
// if the list is ok, let's see what it has inside
else if (list.get(0) instanceof Integer)
System.out.println("int");
else if (list.get(0) instanceof Double)
System.out.println("double");
}
执行的简单主程序:
public static void main(String[] args) {
List<Integer> ints = new ArrayList<Integer>();
List<Double> doubles = new ArrayList<Double>();
check(null);
check(ints);
ints.add(1);
check(ints);
doubles.add(1D);
check(doubles);
}
输出:
null
empty
int
double
class Value {
public void method1(List<Integer> intList) {
}
public void method1(List<Double> doubleList) {
}
}
以上两种方法都不能使用函数重载
看起来这两种方法都将 List
作为参数。
有没有办法区分列表数据类型的参数?
这是错误信息:
Erasure of method method1(List<Integer>) is the same as another method in type Value
有没有其他方法可以在这里使用重载?
您可以使用 method1(List<Object> List)
并使用 instanceof
您不能声明多个具有相同名称以及相同数量和类型的参数的方法,因为编译器无法区分它们。参见 oracle docs。
您可以为此使用泛型:
public void method1(List<?> list) {
}
这样的声明方式,可以查看列表的内容,做自己需要的工作:
public static void check(List<?> list) {
// check null
if (Objects.equals(null, list))
System.out.println("null");
// check empty
else if (list.isEmpty())
System.out.println("empty");
// if the list is ok, let's see what it has inside
else if (list.get(0) instanceof Integer)
System.out.println("int");
else if (list.get(0) instanceof Double)
System.out.println("double");
}
执行的简单主程序:
public static void main(String[] args) {
List<Integer> ints = new ArrayList<Integer>();
List<Double> doubles = new ArrayList<Double>();
check(null);
check(ints);
ints.add(1);
check(ints);
doubles.add(1D);
check(doubles);
}
输出:
null
empty
int
double