【问题标题】:How to get Objects from Array by condition?如何按条件从数组中获取对象?
【发布时间】:2013-01-30 11:25:43
【问题描述】:

这是我的实际代码:

public TerminalGui[] getTerminalGuis() {
    Components comps[] = this.getComponents();
    int i, j = 0;

    for( i = 0; i < comps.length ; i++ ) {
        if( comps[i] instanceof TerminalGui ) {
            j++;
        }
    }

    TerminalGui terminalGuis[j];
    int k = 0;
    for( Component c : comps ) {
        if( c instanceof TerminalGui ) {
            terminalGuis[k] = c;
            k++;
        }
    }
    return terminalGuis;
}

如何做得更好?我想从this.getComponents() 获取所有对象,它们是TerminalGui(接口)的实例。

【问题讨论】:

    标签: java arrays swing oop


    【解决方案1】:

    我会这样做:

    public TerminalGui[] getTerminalGuis() {
        Components comps[] = getComponents();
        List<TerminalGui> list = new ArrayList<TerminalGui>();
    
        if (comps == null) return null;
    
        for( Component c : comps ) {
            if( c instanceof TerminalGui ) {
                list.add(c);
            }
        }
    
        return list.toArray(new TerminalGui[list.size()]);
    }
    

    【讨论】:

      【解决方案2】:

      @NikolayKuznetsov 的答案最好是最少的代码。但在这里你的版本更正了。所以你认识到了可能性。

      public TerminalGui[] getTerminalGuis() {
          Component[] comps = this.getComponents();
          int j = 0;
          for (int i = 0; i < comps.length; i++) {
              if (comps[i] instanceof TerminalGui) {
                  j++;
              }
          }
      
          TerminalGui[] terminalGuis = new TerminalGui[j];
          int k = 0;
          for (Component c : comps) {
              if (c instanceof TerminalGui) {
                  terminalGuis[k] = c;
                  k++;
              }
          }
          return terminalGuis;
      }
      

      【讨论】:

        【解决方案3】:

        您可以使用List

        public TerminalGui[] getTerminalGuis() {
           Components comps[] = this.getComponents();
           List<TerminalGui> terminals = new ArrayList<TerminalGui>();
           int i;
        
              for( i = 0; i < comps.length ; ++i ) {
                 if( comps[i] instanceof TerminalGui ) {
                     terminals.add(comps[i]);
                 }
              }
           return terminals.toArray(new TerminalGui[terminals.size()])
        
        }
        

        【讨论】:

        • 你写了return list. ...,但我认为你的意思是return terminals. ...。我会尽快将此标记为正确答案。
        • 现在我得到一些奇怪的编译器错误:`无法实例化类型 List. Maybe you've got something wrong here I do not see? (found it: new ArrayList` 是必需的。)
        • 哦,是的,我很抱歉,只是把它弄混了,现在应该可以了
        • 对不起,没注意到!非常感谢!
        猜你喜欢
        • 2021-08-02
        • 2020-12-04
        • 1970-01-01
        • 1970-01-01
        • 2020-10-28
        • 1970-01-01
        • 2022-01-01
        • 2020-10-22
        • 1970-01-01
        相关资源
        最近更新 更多