这是我的实际代码:

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

最佳答案

我会这样做:

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

09-25 21:58