3

for-each ループに関連して継承はどのように機能しますか? と の 2 つのクラスがSubClassありSuperClass、次の があるとしますArrayList

/**
* Containes both SuperClass and SubClass instances.
*/
ArrayList<SuperClass> superClasses = new ArrayList<SuperClass>(); 

superClassesのみを選択するような方法で反復することは可能ですかsubClasses?

以下:

for(SubClass subClass : superClasses){
    // Do Foo
}

これはしません。以下は、私が仕事に取り掛かることができる唯一のものです:

for(SuperClass superClass : superClasses){
    if(superClass instanceof SubClass){
        // Do Foo
    }
}

ただし、絶対に必要な場合を除き、使用したくありませんinstanceof。どこでも (StackOverflow、Oracle チュートリアルなど) を読み続けているため、ほとんどの場合、カプセル化を増やすより良い解決策を見つけることができます。これを行うよりエレガントな方法はありますか?

4

4 に答える 4

5

Well you could write a helper method to hide the instanceof test... Guava has a method like this, for example, in Iterables.filter, which you could use like this:

for (SubClass subclass : Iterables.filter(superclasses, SubClass.class)) {
    ...
}

It's only moving the instanceof check though really - it's not getting rid of it. Fundamentally you need that check, because something's got to do the filtering.

于 2013-07-03T12:11:37.690 に答える
2

最初のアプローチ ( for (SubClass subClass : superClasses)) は、そこに tyoe のオブジェクトしかないことをコンパイラーが保証できないため、機能しませんSubClass

Java (外部ライブラリなし) では、Class. したがって、instanceofこれを行う通常の方法です。

于 2013-07-03T12:12:08.397 に答える
1

instanceof would work absolutely fine in this situation. But if you really do have reasons for not using it you could always give the superclass some variable, Boolean skipMe = true, and change that to false in the subclass if you wanted.

But I suggest using instanceof

于 2013-07-03T12:12:07.850 に答える