0

这是我的实际代码:

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

4

3 回答 3

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()]);
}
于 2013-01-30T11:29:43.523 回答
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;
}
于 2013-01-30T11:31:45.957 回答
2

您可以使用列表

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

}
于 2013-01-30T11:32:06.377 回答