Is there any way in Java to avoid instantiating a stateless object? There is no real difference between a static function and a stateless object for example:
class CompareInts {
Integer compare(Integer a, Integer b) {
return a.compareTo(b);
}
static Integer compare(Integer a, Integer b) {
return a.compareTo(b);
}
Functionality wise these two alternatives do the same thing and in general every stateless class can be converted to a static function. There are two main differences though:
Therefore a static function is better in theory because it provides all the functionality of a stateless class but without the runtime and memory overheads. A static function is much less powerful in Java because it can't be called through a Generic type. Is there any way to benefit from both worlds?
Edit
I want to write a generic class as follows:
class Array<Type, Comparator> {
Type[] elements;
// array stuff
Type getMax() {
Type maxElement = Type.getSmallestLegalValue();
for (Type element : elements) {
maxElement = Comparator.compare(maxElement, element) > 0 ? maxElement : element;
}
return maxElement;
}
}
I can't write this. I have to accept a Comparator in Array's constructor and create aComparator interface that CompareInts implements.
You need an instance, just as you need a function in functional languages where functions are first class citizens.
But you don't need to create a new instance each time, you can store that instance in a static variable of your Comparator class.
Generics can be used with static methods:
static <T extends Number & Comparable<T>> int compare(T a, T b) {
return a.compareTo(b);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With