Proposal: Accepting a subclass as an element type in a for loop

Jean Louis Ardoint ARDOINT at
Mon May 18 02:36:45 PDT 2009

Hi Joe,

Thank you for your answer and your pointer to the interesting use of 
Class.cast in ElementFilter. 

I agree that what I proposed can be done by using library classes or 
methods, yet such a solution comes with a cost in terms of performance and 
memory. In ElementFilter for example, the whole collection gets 
duplicated. This could be avoided by implementing specific Iterable and 
Iterator interfaces, yet you would still get two allocations for some code 
that would not require any by writing it manually or using the proposal. 
Eventually better JVMs will remove the cost of those extra allocated 
objects but it is not the case as of today.

Still, the problem addressed by my proposal seems to be too specific. I 
think it could be made more interesting if it took into account filtering 
in a loop in a broader sense, for example by adding an optional test to a 
foreach loop:

for (Rectangle r : shapes; r != null && r.length() * r.width() < 12)

that would replace:
for (Shape s : shapes) {
  if (s instanceof Rectangle) {
    Rectangle r = (Shape)s;
    if (r != null && r.length() * r.width() < 12)


"Joseph D. Darcy" <Joe.Darcy at Sun.COM>
Jean-Louis Ardoint <jlardoint at>
coin-dev at
15/05/2009 07:24
Re: Proposal: Accepting a subclass as an element type in a for loop
Sent by:
Joe.Darcy at Sun.COM

Jean-Louis Ardoint wrote:
> I'm maybe a bit too late. Here's my proposal anyway.
> -- Jean-Louis Ardoint
> Accepting a subclass as an element type in a for loop

Catching up on proposal comments, I agree with the previous replies on 
the list that this scenario is more than adequately handled by filtering 
library methods.

FYI, one class implementing these kinds of filters in the JDK is 


Sauf indication contraire ci-dessus:/ Unless stated otherwise above:
Compagnie IBM France
Siège Social : Tour Descartes, 2, avenue Gambetta, La Défense 5, 92400 
RCS Nanterre 552 118 465
Forme Sociale : S.A.S.
Capital Social : 609.751.783,30 ?
SIREN/SIRET : 552 118 465 02430

More information about the coin-dev mailing list