Java 为什么可以';我有两个带ArrayList参数的方法吗?
为什么我不能创建两个重载方法,它们的参数都是数组列表,但数据类型不同Java 为什么可以';我有两个带ArrayList参数的方法吗?,java,exception,generics,methods,arraylist,Java,Exception,Generics,Methods,Arraylist,为什么我不能创建两个重载方法,它们的参数都是数组列表,但数据类型不同 public class test { public static void main(String[] args){ ArrayList<Integer> ints = new ArrayList<Integer>(); ints.add(1); ints.add(2); ints.add(3); ints.add(4); ints.add(5);
public class test {
public static void main(String[] args){
ArrayList<Integer> ints = new ArrayList<Integer>();
ints.add(1);
ints.add(2);
ints.add(3);
ints.add(4);
ints.add(5);
showFirst(ints);
ArrayList<Double> dubs = new ArrayList<Double>();
dubs.add(1.1);
dubs.add(2.2);
dubs.add(3.3);
dubs.add(4.4);
dubs.add(5.5);
showFirst(dubs);
}
public static void showFirst(ArrayList<Integer> a)
{
System.out.println(a.remove(0));
}
public static void showFirst(ArrayList<Double> a)
{
System.out.println(a.remove(0));
}
}
编辑:
如果我想在需要数据类型的地方做一些事情,例如:
public static int[] reverseInArray(ArrayList<Integer> a)
{
int n = a.size();
int[] b = new int[n];
while(n > 0)
{
b[n] = a.remove(0);
n--;
}
return b;
}
public static double[] reverseInArray(ArrayList<Double> a)
{
double n = a.size();
double[] b = new int[n];
while(I > 0)
{
b[n] = a.remove(0);
n--;
}
return b;
}
public static int[]reverseInArray(数组列表a)
{
int n=a.size();
int[]b=新的int[n];
而(n>0)
{
b[n]=a.remove(0);
n--;
}
返回b;
}
公共静态双[]反向数组(ArrayList a)
{
双n=a.尺寸();
双[]b=新整数[n];
而(I>0)
{
b[n]=a.remove(0);
n--;
}
返回b;
}
在运行时,由于以下原因,每个ArrayList
都将转换为ArrayList
(原始)。所以,只要有一个方法接收List,泛型只在编译时强制执行。在运行时,ArrayList
是一个ArrayList
在这种特殊情况下,您可以将这两种方法结合使用,不过:
public static void showFirst(ArrayList<? extends Number> a)
{
System.out.println(a.remove(0));
}
public static void showFirst(ArrayList),因为泛型在运行时被擦除。换句话说,您的代码不知道这两个方法不同。事实上,您还有一个编译器错误,您没有告诉我们:
Method showFirst(ArrayList<Integer>) has the same erasure showFirst(ArrayList<E>) as another method in type Main
方法showFirst(ArrayList)与类型Main中的另一个方法具有相同的擦除showFirst(ArrayList)
仅使用此方法,因为泛型仅在compile中可用,因此,两个方法都编译为相同的签名。因此,调用哪个方法是不明确的
public static void showFirst(ArrayList<? extends Number> a)
{
System.out.println(a.remove(0));
}
publicstaticvoidshowfirst(ArrayList…因为,您的泛型参数在运行时是未知的,因此您的重写方法共享一个不明确的签名。查看类型擦除。这并不能回答问题。-1泛型仅在运行时可用,
在编译时不为true;)@Nachokk:更正了,这是一个输入错误。+1实际上,List
将是最合适的。@PaulBellora更新了答案,反映了List
+1之间的差异,作为建议。.方法的名称应尽可能具有声明性。.如果调用方法showFirst
我希望该方法不会删除元素f从名单上!
public static void showFirst(ArrayList<? extends Number> a)
{
System.out.println(a.remove(0));
}
Method showFirst(ArrayList<Integer>) has the same erasure showFirst(ArrayList<E>) as another method in type Main
public static void showFirst(ArrayList<? extends Number> a)
{
System.out.println(a.remove(0));
}