How to avoid repetition when working with primitive types?
Posted
by I82Much
on Stack Overflow
See other posts from Stack Overflow
or by I82Much
Published on 2010-03-19T19:57:34Z
Indexed on
2010/03/19
20:01 UTC
Read the original article
Hit count: 294
java
|best-practices
I have the need to perform algorithms on various primitive types; the algorithm is essentially the same with the exception of which type the variables are. So for instance,
/**
* Determine if <code>value</code> is the bitwise OR of elements of <code>validValues</code> array.
* For instance, our valid choices are 0001, 0010, and 1000.
* We are given a value of 1001. This is valid because it can be made from
* ORing together 0001 and 1000.
* On the other hand, if we are given a value of 1111, this is invalid because
* you cannot turn on the second bit from left by ORing together those 3
* valid values.
*/
public static boolean isValid(long value, long[] validValues) {
for (long validOption : validValues) {
value &= ~validOption;
}
return value != 0;
}
public static boolean isValid(int value, int[] validValues) {
for (int validOption : validValues) {
value &= ~validOption;
}
return value != 0;
}
How can I avoid this repetition? I know there's no way to genericize primitive arrays, so my hands seem tied. I have instances of primitive arrays and not boxed arrays of say Number objects, so I do not want to go that route either.
I know there are a lot of questions about primitives with respect to arrays, autoboxing, etc., but I haven't seen it formulated in quite this way, and I haven't seen a decisive answer on how to interact with these arrays.
I suppose I could do something like:
public static<E extends Number> boolean isValid(E value, List<E> numbers) {
long theValue = value.longValue();
for (Number validOption : numbers) {
theValue &= ~validOption.longValue();
}
return theValue != 0;
}
and then
public static boolean isValid(long value, long[] validValues) {
return isValid(value, Arrays.asList(ArrayUtils.toObject(validValues)));
}
public static boolean isValid(int value, int[] validValues) {
return isValid(value, Arrays.asList(ArrayUtils.toObject(validValues)));
}
Is that really much better though? Any thoughts in this matter would be appreciated.
© Stack Overflow or respective owner