Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: Jim Janney Newsgroups: comp.lang.java.programmer Subject: Re: Converting Sets Date: Thu, 02 Feb 2012 13:13:10 -0700 Organization: not at this time Lines: 50 Message-ID: <2pliol804p.fsf@shell.xmission.com> References: <11fki7dcr12je80bqi6q7ml6f0tc78965a@4ax.com> <4f2a767d$0$449$426a34cc@news.free.fr> <4f2aa4fe$0$6897$426a74cc@news.free.fr> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx04.eternal-september.org; posting-host="PF2DXJoCGeGUb03TdAwosA"; logging-data="17599"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18bOhPHpQUdnjjuCeCTpUlW" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:Z1xuIWJBfN69huuAUhUaKDskrzo= sha1:OYyKKKfqaXkjx+JPCvijClBWS4k= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:11715 markspace <-@.> writes: > On 2/2/2012 7:06 AM, Mayeul wrote: >> On 02/02/2012 14:32, Roedy Green wrote: > >>> Ah, but this this you created is NOT a Set. You cannot add >>> arbirary Y to it, just more X. I feel queasy. How could the compiler >>> keep track that setOfY could only contain X. > >> >> It cannot. > > > I think this is covered in Effective Java. Generics are a compile > time thing. If you want runtime, you have to roll your own (I don't > know of any classes in the API that allow you to have a runtime type > parameter, although I guess there may be some). > > class MySet extends SomeSet { > > Class type; > > MySet( Class type ) { this.type = type; } > > void add( Object o ) { > if( o instanceof type ) super.add( o ); > } > } > > I think is the above is the gist of how EJ handles it. Add a type > token (the "type" variable) and test for types as they are added. If > you want generics too, add them in: > > class MySet extends Set { > > Class type; > > MySet( Class type ) { this.type = type; } > > void add( T o ) { > if( o instanceof type ) super.add( o ); > } > } > > Not compiled, but I think that gives the right idea. See checkedSet in java.util.Collections. -- Jim Janney