Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiation of stateless objects in Java

Tags:

java

static

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:

  1. Instantiating a static class takes both time and memory where neither are needed. You only really need to store the code you don't need to allocate an object on the heap and a pointer to a vtable.
  2. static functions are very limited in Java. They can not be used with Generics, the static compare can never be used by a class that must receive a compare.

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.

like image 740
Benjy Kessler Avatar asked Aug 12 '26 07:08

Benjy Kessler


2 Answers

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.

like image 122
Denys Séguret Avatar answered Aug 13 '26 21:08

Denys Séguret


Generics can be used with static methods:

static <T extends Number & Comparable<T>> int compare(T a, T b) {
    return a.compareTo(b);
}
like image 36
sp00m Avatar answered Aug 13 '26 21:08

sp00m