如何从超类Set中过滤子类对象并将其添加到子类List中

How to filter subclass objects from superclass Set and add them to subclass List

给出了具有以下 UML Class 图的复合设计模式:

ClassA是抽象的,items是用aHashSet<A>实现的。 我想通过遍历给定的 HashSet<A> 来实现 Class B 的 getAllC() 方法,检查当前对象是否来自类型 C 并(如果为真)将其添加到 List<C>.

我的问题是我无法想出将 Class C - 对象插入新的 List<C> 的正确想法,因为给定的 HashSet<A> 具有不同的泛型参数.

到目前为止我的思路在代码中给出(显然行不通,只是想展示我最初的“方法”):

public class B {

   private Set<A> items = new HashSet<A>();

   public List<C> getAllC() {

      List<C> c_list = new ArrayList<C>();

      for (A a : items) {
         if (a.getClass().equals(C.class)) {
            c_list.add(a);
         }
      }
      return c_list; 
   }
}

你可以使用流,很简单:

items.stream()
     .filter(el -> el instanceof C) // consider only the one you want
     .map(el -> (C) el) // cast them
     .collect(Collectors.toList()); // collect them

但是如果你想保留你的命令式版本,你可以这样做:

public class B {

   private Set<A> items = new HashSet<A>();

   public List<C> getAllC() {

      List<C> c_list = new ArrayList<C>();

      for (A a : items) {
         if (a instanceof C) { 
              c_list.add((C) a); 
         }
      }
      return c_list; 
   }
}

有想做的:

  1. 检查类型是否为 a instanceof C
  2. 投射你的对象
public class B {

   private Set<A> items = new HashSet<A>();

   public List<C> getAllC() {

      List<C> c_list = new ArrayList<C>();

      for (A a : items) {
         // equals() is intended to compare two object. 
         // You want to know if the type is equals. This is done by using instanceof
         // if (a.getClass().equals(C.class)) {
         if (a instanceof C)
            c_list.add((C) a); // know you cast your object to its new type
         }
      }
      return c_list; 
   }
}