I'm solving algorithmical problems, and i want to write custom functions and predicates that can be applied to collections. Recently, i started using Google Collections and it is just wonderful for this task.
I want to use BigInteger and BigDecimal same way, as i would use any other numbers. Without pondering how it should be done, i decided to make an extra layer of abstraction(Class E).
If it is unclear what I am trying to do, here is an example:
I.range(1,999).multiplication(I.range(1,999)).palindromes().max().echo(2);
- return collection of sequence 1:999 (x2)
- return 2 collections every item with method times() transform
- return collection of every item what passes palindromes filter
- return maximum element E<?> of 3. result
- return element E<?> and invoke method toString with radix 2 (binary) and print it to screen
Class E is defined as:
public class E<T extends Number & Comparable<? super T>> extends Number implements Comparable<E<T>> {//...
Class C is defined as:
public class C<T extends E<NC>, NC extends Number & Comparable<? super NC>> implements Collection<T> {
This is what i want to make working in class C.
public Collection<T> multiplication(T value) {
return Collections2.transform(this, new Function<T, T>() {
@Override
public T apply(T in) {
return in.times(value);
}
});
}
Before i used following code, in class E
/** Multiplies 2 numbers */
public E<?> times(E<?> elem) {
if (this.value == null || elem.value == null) return E.Null();
if (this.value instanceof Integer) {
return E.with(I, this.intValue() * elem.intValue());
} else if (this.value instanceof Long) {
return E.with(L, this.longValue() * elem.longValue());
} else if (this.value instanceof Float) {
return E.with(F, this.floatValue() * elem.floatValue());
} else if (this.value instanceof Double) {
return E.with(D, this.doubleValue() * elem.doubleValue());
} else if (this.value instanceof BigInteger) {
return E.with(BI, this.BigIntegerValue().multiply(
elem.BigIntegerValue()));
} else if (this.value instanceof BigDecimal) { return E.with(BD,
this.BigDecimalValue().multiply(elem.BigDecimalValue())); }
return E.Null();
}
What should i change, so that writing custom functions and predicates would involve minimal amount of 'suckiness'.
Edit:
A well, changed C to:
public class C<T extends E<?>> extends ArrayList<T> {
And just suppressed generic wildcard casting warnings like
public Collection<T> multiplication(Collection<T> value) {
C<T> result = new C<T>();
for (T t : value)
result.addAll(multiplication(t));
return result;
}
public Collection<T> multiplication(final T value) {
return Collections2.transform(this, new Function<T, T>() {
@SuppressWarnings("unchecked")
@Override
public T apply(T in) {
return (T) in.times(value);
}
});
}
So if the types match, this works.