1

I have the following code:

public class A {
  private int id;
  private String name = null;
  private static int counter = 0;
  private static Stack<A> pool = new Stack<>();

  private A (){
    A.counter += 1;
    setId();
  }

  private void setId(){
    id = A.counter;
  }

  public void setName(String name) {
    this.name = name;
  }

  public static A getInstance() {
   A element;
   try {
        element = pool.pop();
      } catch (EmptyStackException e) {
        element = new A();
      }
    return element;
  }

  public static void returnInstance(A element) {
    pool.push(element);
  }
}

How can I externalize the getInstance(), returnInstance() and the private static Stack pool to an abstract class?

  • class A is not a abstract class – janith1024 Jun 18 '18 at 10:03
  • 1
    Simply put, you cannot. A static method cannot reference a non-static generic type, as explained [here](https://stackoverflow.com/questions/936377/static-method-in-a-generic-class/936951). – Lewis_McReu Jun 18 '18 at 10:19

1 Answers1

1

As said in the comments, you can not. But you can make a Helper class to which you then delegate:

public final class Pool<T> {
     private final Stack<T> pool = new Stack<>();
     private final Supplier<? extends T> provider;

     public Pool(Supplier<? extends T> provider){
         this.provider = provider;
     }

     public T getInstance() {
         T element;
         try {
             element = pool.pop();
         } catch (EmptyStackException e) {
             element = provider.get();
         }
         return element;
     }

     public void returnInstance(T element) {
         pool.push(element);
     }
}

And in class A:

public class A{
    private int id;
    private String name = null;
    private static int counter = 0;

    public static final Pool<A> pool = new Pool<>(A::new);

    private A (){
        A.counter += 1;
        setId();
    }

    private void setId(){
        id = A.counter;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Which then can be used as follows:

A a = A.pool.getInstance();
// do some stuff with a
A.pool.returnInstance(a);

This class Pool can now be used everywhere you want to have the same mechanism.

Lino
  • 19,604
  • 6
  • 47
  • 65
  • error: cannot find symbol private final Supplier extends T> provider; and what means the "new Pool<>(A::new)" part? Is it a shell object of A required for this.provider = provider; when the stack is empty? – Dimitar Dimitrov Jun 19 '18 at 07:59
  • I got it - Functional Interface from Java8.. I should mention the API to resolve the error... – Dimitar Dimitrov Jun 19 '18 at 08:57
  • @DimitarDimitrov `A::new` is equal to `() -> new A()` which is like passing a method which always returns a new `A` instance to the constructor of `Pool` – Lino Jun 19 '18 at 15:21