【问题标题】:Pass Arraylist of child objects and parent objects to the same method将子对象和父对象的 Arraylist 传递给同一个方法
【发布时间】:2019-01-29 19:21:58
【问题描述】:

我有扩展 A 类的 B 类。如何在 C 类中编写一个方法,该方法可以接收包含 B 类或 A 类对象的 ArrayList 而无需覆盖?

public class A {
    //Some methods here
}

public class B extends A {
    //Some methods here
}

public class C {

    public Static void main(String[] args){
        ArrayList<A> one = new ArrayList<>();
        one.add(new A());

        ArrayList<B> two = new ArrayList<>();
        two.add(new B())

        doStuff(one);
        doStuff(two);
    }

    public void doStuff(args){
       //go ahead do stuff
    }
}

【问题讨论】:

    标签: java inheritance multiple-inheritance


    【解决方案1】:

    使用带有通配符的泛型表示您将接受任何 A扩展 A 的列表。

    public void doStuff(List<? extends A> list) {
        ...
    }
    

    如果您想捕获您要编写的确切列表类型:

    public <T extends A> void doStuff(List<T> list) {
        ...
    }
    

    然后你可以在方法中使用T。如果您不需要T,请坚持第一种方法。

    【讨论】:

      【解决方案2】:

      这应该可行:

      public void doStuff(List<? extends A) someList)
      

      ...然后,这成为可能:

      List<A> ones = new ArrayList<>();
      one.add(new A());
      
      List<B> two = new ArrayList<>();
      two.add(new B())
      
      doStuff(one);
      doStuff(two);
      

      这里还有一件重要的事情:使用List 作为您的类型。您只在创建列表时指定具体的实现类,但在任何其他地方,请避免使用实际的类名!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多