I have a byte
array and a List
of a custom object ByteRule
and I'm needing to loop around and perform an operation on both but only as long as one of both is available, the original method is as follows:
private final List<ByteRule> rules;
@Override
public boolean match(final InetAddress addr)
{
final byte[] bytes = addr.getAddress();
for(int i = 0; i < this.rules.size() && i < bytes.length; i++)
{
final int value = bytes[i] < 0 ? (int) bytes[i] + 256 : bytes[i];
if(!this.rules.get(i).match(value))
{
return false;
}
}
return true;
}
Obviously the this.rules.get(i)
on every iteration is inefficient, however as I need to maintain a counter, an enhanced for
loop means keeping a separate counter and performing a check on it every time like so (list declaration skipped for space):
@Override
public boolean match(final InetAddress addr)
{
final byte[] bytes = addr.getAddress();
int counter = 0;
for(final ByteRule rule : this.rules)
{
if(counter + 1 == bytes.length) break; //In case there aren't enough bytes
final int value = bytes[counter] < 0 ? (int) bytes[counter] + 256 : bytes[counter];
if(!rule.match(value))
{
return false;
}
counter++;
}
return true;
}
Is there a cleaner/more efficient solution to this problem that I'm missing?
this.rules.get(i)
on every iteration is inefficient That is not obvious to me at all. \$\endgroup\$0xFF
. \$\endgroup\$