【问题标题】:Method Overloading in java - using List Type [duplicate]java中的方法重载-使用列表类型[重复]
【发布时间】:2016-05-04 07:48:50
【问题描述】:
class Value {
    public void method1(List<Integer> intList) {

    }

    public void method1(List<Double> doubleList) {

    }

}

以上两种方法都不能使用函数重载。

看起来这两种方法都将List 作为参数。 有没有办法区分 Lists 数据类型的参数?

这是错误信息:

Erasure of method method1(List<Integer>) is the same as another method in type Value

还有其他方法可以在这里使用重载吗?

【问题讨论】:

    标签: java overloading


    【解决方案1】:

    您不能声明多个具有相同名称、相同数量和类型的参数的方法,因为编译器无法区分它们。见oracle docs

    【讨论】:

      【解决方案2】:

      您可以为此使用泛型:

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

      执行的简单main:

      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
      

      WORKING IDEONE DEMO

      【讨论】:

      • 如果两种方法必须执行不同的操作,会有什么帮助?
      • @SergheyBishyr 请检查我的编辑:)
      【解决方案3】:

      您可以使用 method1(List&lt;Object&gt; List) 并使用 instanceof 检查方法中的类型

      【讨论】:

      • 那行不通。您无法在运行时检测到 List&lt;Integer&gt;List&lt;Double&gt; 之间的区别
      • 是否有可能通过执行以下操作:if List[0] instnaceof Integer ?
      • 当然,但这很不可靠。如果它是整数和双精度的混合列表怎么办?如果它是一个空列表怎么办?
      • 确实如此,这意味着之前需要进行大量检查。我的坏
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多