Re: syntatic sugar IN keyword.
Tom McGlynn wrote:
For some cases perhaps you could use something like
if (in(1,2,3,4,5,6,7,8,9).contains(i)) {...}
with a method
static Set in(Object... data) {
Set mySet = new HashSet();
for (Object element: data) mySet.add(element);
return mySet;
}
If you use this a lot you could have this in some Utility class and do
a
import static Utility.in;
That's pretty close to your original request. I think autoboxing will
take care of the primitives but I haven't tried this. You'd need to
be chary of
if (in(1,2,3...).contains(1.0)) ...
If there were a special syntax it would likely be easier for the
compiler to automatically extract constant <in> lists out of loops but
doing that manually shouldn't be too difficult. There would be harder
with
for (somebigloop) {
method1(x)
}
method1(x) {
if (in(1,2,3).contains(x)) ( ...}
}
where a special syntax would make it a lot easier for the compiler to
recognize the constant expression and compute the hash only one time
rather than for each loop, but in such a case probably the Set should
not be a local variable that needs to be recomputed, but a class
member.
Special syntax - costly change that provides slight compression of
code that you basically write only once per project anyway.
You can prevent recalculation of 'in()' results by passing the
returned 'Set' instead of recalculating it.
void method1( Foo x, Set <Foo> inset )
{
if ( inset.contains( x ))
{ ..., }
}
which seems silly. Just create immutable 'Set's of what you want to
model as sets, and use 'Set#contains()' to model containment within a
set.
void methodThatNoLongerNeedsMethod1( Foo x )
{
final Set <Foo> inset = Collections.unmodifiableSet( in( foo0,
foo1, foo2, foo3 ));
while ( reallyLongLastingCondition() )
{
if ( inset.contains( x ))
{ ... }
}
}
Depending on your logic, 'inset' can be local, instance or class
scope. Depending on the number of loop iterations, the use of a
'HashSet' under the hood can really help performance even for fairly
small sets.
This is not a verbose idiom, certainly not by Java standards.
--
Lew