为什么我不能有两个带ArrayList参数的方法?

use*_*330 3 java generics methods exception 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);

    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));
  }
}
Run Code Online (Sandbox Code Playgroud)

我在eclipse中,它强调了导致代码为红色的问题并给出了这样的信息: Method showFirst(ArrayList<Integer>) has the same erasure showFirst(ArrayList<E>) as another method in type test

我能让它工作的唯一方法是添加其他参数,例如, int bafter showFirst(ArrayList<Integer> a, int bafter showFirst(ArrayList<Double> a.

有没有办法让这段代码按照我的意图运作?如果没有,我想知道为什么会这样.

运行该程序会生成以下错误消息:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  The method showFirst(ArrayList<Integer>) in the type test is not applicable for the arguments (ArrayList<Double>)
at test.test.main(test.java:25)
Run Code Online (Sandbox Code Playgroud)

编辑:

使用或者,如果我想做我需要数据类型的事情,例如:

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;
  }
Run Code Online (Sandbox Code Playgroud)

Lui*_*oza 12

在运行时,由于类型擦除,每个ArrayList<Whatever>都将转换为ArrayList(原始).所以,只需要一个接收的方法.List<? extends Number>

//renamed to show what the method really does
public static void removeFirst(List<? extends Number> a) {
    System.out.println(a.remove(0));
}
Run Code Online (Sandbox Code Playgroud)

请注意,上述方法将只对ListS( ArrayList,LinkedList以及其他实施方式List),其声明来保存从延伸的类Number.如果你想/需要一个方法来从中删除List任何类型的第一个元素,请使用List<?>:

public static void removeFirst(List<?> a) {
    System.out.println(a.remove(0));
}
Run Code Online (Sandbox Code Playgroud)

请记住始终编程到接口而不是特定的类实现.

  • +1事实上,`List <?>`将是最合适的. (2认同)