如何在 Java 的嵌套列表结构中获取嵌套项

How to get nested items in a nested list structure in Java

我想从一个结构中获取所有嵌套项,该结构包含项本身以及包含项本身的项: 将项目添加到此列表时,我不知道它将是什么类型的项目,因为我只是将一般类型的项目(称为 SuperItem)添加到此列表。 (SubItem和Item同样继承自SuperItem)

例如,最后我有一个这样的 SuperItems 列表:

SuperItem[子项 A、子项 B、项 C、子项 D]

虽然,项目 C 也包含子项目。所以如果我有一个看起来像这样展开的嵌套结构:

UnfoldedSuperItem[子项 A、子项 B、子项 C1、子项 C2、子项 C3、子项 D]

这是我想要返回的列表。不过,目前我在调用 getAllSubItems().

时只能从 SuperItem 列表中获取 A、B 和 D,而不能获取 C1、C2 和 C3
public class Item extends SuperItem{
    List<SuperItem> superItems;
    List<SubItem> subItems;

    public Item() {
        super();
        superItems = new LinkedList<>();
        subItems = new LinkedList<>();
    }


    public void addItem(SuperItem s) {
        if (!superItems.contains(s))    {
            superItems.add(s);
        }
    }

    //[... a remove method is also in this class, not included here as not in scope]

    public List<subItem> getAllSubItems() {
        for (superItem s: superItems) {
            if (s.getClass() == SubItem.class) {
                if (!subItems.contains(s)) {
                    subItems.add((SubItem) s);
                }
            } else {
                //if it is a item, somehow call the method getAllSubItems() on itself
            }
        }
        return subItems;
    }
}

这里唯一缺少的是当我来到这个不是子项目的 C-Item 时。我有点想打开 C 以获取其中的所有嵌套项。

另外重要的是: Item 也可以包含 Items 本身。所以列表也可以像这样:

超级项目[项目 A、项目 B、项目 C、子项目 D]

然后展开:

SuperItemUnfolded1[项目 A1、项目 A2、子项目 B1、子项目 B2、项目 C1、项目 C2、子项目 D]

然后展开更多:

SuperItemUnfolded2[子项 A1.1、子项 A1.2、子项 A2.1、子项 A2.2、子项 B1、子项 B2、项 C1.2 等等])

也许您正在寻找这样的东西:

public class SuperItem {
   List<Item> superItems = new LinkedList<Item>();
   List<Item> currentSubItems = null;


   public void addItem(Item s, boolean isNewSublist) {
      if (isNewSublist || currentSubItems == null) {
         currentSubItems = new LinkedList<Item>();
         superItems.add(currentSubItems);
      }
      if (!currentSubItems.contains(s))    {
         currentSubItems.add(s);
      }
      ...
   }

   public List<Item> getAllSubItems() {
      List<Item>subItems = new List<Item>();
      for (List<Item> superItem : superItems) {
         for (Item item : superItem.subItems) {
      ...
      return subItems;
   }
}

细节会根据你想要完成的具体目标而有所不同,但基本上听起来像你:

  1. 想要列表的列表,包含"items"。
  2. 您想将此 "list of lists" 封装在 class 中。
  3. class 应该为 "add" 项和 "list" 项提供方法。
  4. 有一件事我不清楚 - "items" 应该在 "sublist" 中是唯一的,还是在整个 "list of lists" 对象中是唯一的?我选择了前者。

您可能还对 Java 合集感兴趣,例如 Dictionary, Map or Set

"Set" 可能对您特别有帮助:

https://www.tutorialspoint.com/java/java_set_interface.htm

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.

The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.