如何通过条件从数组中获取对象?

时间:2013-01-30 11:25:43

标签: java arrays swing oop

这是我的实际代码:

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(接口)实例的所有对象。

3 个答案:

答案 0 :(得分:2)

我会这样做:

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()]);
}

答案 1 :(得分: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;
}

答案 2 :(得分:2)

您可以使用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()])

}