0

ShapeスーパークラスとNestedShapeサブクラスがあります。NestedShapeサブクラスには、ネストされた ArrayList (' ' )ShapesListがあります。Shapesの「含む」メソッドを実装する必要がありますNestedShape。このメソッドは、Shapeオブジェクトが与えられたときに、その形状が の に存在するかどうかをチェックする必要がありNestedShapeますShapeList。現時点での私の実装は非常に単純です。 で ArrayList.contains()メソッドを呼び出すだけですShapesList

ただし、実装する必要がある 'contains' メソッドでは、検索対象の形状が に含まれていないことも確認する必要がNestedShapeありますShapesListShapeListこれを行うための明白な方法は、 を使用して、 内のinstanceofそれぞれが であるかどうかを確認することです。次に、それが. ただし、これがこれを行う良い方法であるかどうかはわかりません-の使用は嫌われていると聞いています(また、再帰を使用するという私の考えが機能するかどうかもわかりません)。ShapeShapeListNestedShapeNestedShapeinstanceof

誰かがこの問題を解決するより良い方法を提案できますか?

ありがとう :)

4

3 に答える 3

1

2 つのアイデア:

  1. NestedShape拡張させないShapeで、別々に処理してください。

  2. すべてShapeを「入れ子」にします。単一の形状で常にfalseを返しますcontains()

于 2013-05-20T07:46:37.150 に答える
1

If

  • the performance of the contains() method is your concern and
  • NestedShape are immutable meaning the list of nested Shape instances once set will never change

then I would suggest a slightly different approach.

Instead of recursively iterating though all the NestedShapes you can add a Set inside the Shape class that will store the references to all the NestedShape instances for which it is possible to access this Shape instance.

于 2013-05-20T08:19:20.517 に答える