加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 02:03:19 所属栏目:Java 来源:网络整理
导读:为什么我不能创建两个重载方法,其参数既是数组列表,又有不同的数据类型? public class test { public static void main(String[] args){ ArrayListInteger ints = new ArrayListInteger(); 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));
  }
}

我在eclipse中,它强调导致代码为红色的问题并给出此消息:方法showFirst(ArrayList< Integer>)具有相同的擦除showFirst(ArrayList< E>)作为类型测试中的另一种方法

我可以让它工作的唯一方法是我添加其他参数,例如showFirst之后的int b(ArrayList< Integer> a和showFirst之后的int b(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)

编辑:

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

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

解决方法

在运行时,每个ArrayList< Whatever>由于 type erasure,将转换为ArrayList(raw).因此,只需要一个接收List&lt ;?的方法扩展数字>.

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

请注意,上面的方法仅适用于Lists(ArrayList,LinkedList和List的其他实现),它们声明保存从Number扩展的类.如果您想要/需要一个方法从List中删除包含任何类型的第一个元素,请使用List<?>代替:

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

记得总是program to interfaces instead of specific class implementation.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读