繁体   English   中英

通过接口将一个数组列表传递给包装类中的另一个数组列表

[英]Pass one arraylist to another in wrapper class with interface

你有界面。

public interface Group {
    public void assemble();
}

您有两个实现该接口的类。

public class Block implements Group {

    public void assemble() {
        System.out.println("Block");
    }
}

public class Structure implements Group {
  // Collection of child groups.
  private List<Group> groups = new ArrayList<Group>();

  public void assemble() {
    for (Group group : groups) {
      group.assemble();
    }
  }

  // Adds the group to the structure.
  public void add(Group group) {
    groups.add(group);
  }

  // Removes the group from the structure.
  public void remove(Group group) {
    groups.remove(group);
  }
}

创建对象后:

Structure structure = new Structure();
Structure structure1 = new Structure();

并在结构实例中填充ArrayList:

structure1.add(new Block());
structure1.add(new Block());

您可以通过:structure.add(structure1)

但是,当您分别将一个ArrayList传递给另一个时,必须使用addAll方法:

List<Group> groups = new ArrayList<Group>();
List<Group> groups1 = new ArrayList<Group>();
groups1.addAll(groups);

我的问题是为什么这行得通?


示例来自: http : //javapapers.com/design-patterns/composite-design-pattern/

没有传递ArrayList ,而是传递Structure Structure不是ArrayList它是Group的后代。 而且此结构内部有自己的list 有了它自己的assemble()方法的实现。

因为您使用addAll方法。 您将一个列表添加到另一个列表。 你为什么混淆?

    /**
 * Appends all of the elements in the specified collection to the end of
 * this list, in the order that they are returned by the
 * specified collection's Iterator.  The behavior of this operation is
 * undefined if the specified collection is modified while the operation
 * is in progress.  (This implies that the behavior of this call is
 * undefined if the specified collection is this list, and this
 * list is nonempty.)
 *
 * @param c collection containing elements to be added to this list
 * @return <tt>true</tt> if this list changed as a result of the call
 * @throws NullPointerException if the specified collection is null
 */
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
    int numNew = a.length;
ensureCapacity(size + numNew);  // Increments modCount
    System.arraycopy(a, 0, elementData, size, numNew);
    size += numNew;
return numNew != 0;
}

这两个示例做了非常不同的事情。 当你做

structure.add(structure1);

您在此处添加了两个层次结构,因为如果您将其视为树,则在structure本身之下的Group级添加了structure1 Group 属于structure1Block在此处仍处于第二级,仍附加到structure1

但是当你这样做

groups1.addAll(groups);

您在这里仅获得单级层次结构,因为您没有添加Group而是将其所有成员直接添加到groups1下方,作为任何可能是其子级的Block的兄弟。

因为您将groups1实例化为ArrayList。 创建结构时,它不是ArrayList。

我认为您“可能”表示要执行以下操作:

   public List<Group> groups = new ArrayList<Group>();

将以上的访问修饰符更改为public。

然后,您将可以执行以下操作:

    structure.groups.addAll...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM