Task: Create a class named ConnectionManager that manages a fixed array of Connection objects. A client programmer should not directly create Connection objects, but can only receive them using a static method in the ConnectionManager class. When the ConnectionManager class has run out of objects, it should return a null reference.

Here's what I got

public class ConnectionManager { private static Connection[] limitObjects = new Connection[5]; public static Connection getObject(){ return Connection.createNewObject(); } } class Connection{ private Connection(){} public static Connection createNewObject(){ return new Connection(); } } 

I just can’t figure out how to implement this. “ When the ConnectionManager class has reached its supply of objects, it should return the null reference. ”?.

  • I’m from the .net world, but I assume that the task [should be] Connection [] to be interleaved and initialized in the static constructor (put 5 Connection objects in it), and in the ConnectionManager.getObject method, retrieve an object from the stack, first checking how many links to Connection are left , and if they are not left to return null - kimaman2
  • Thanks for the tip, but it seems to me that everything should be much simpler. You see, I read the book and in it, before this task, the stacks have not yet been considered) - dexploizer
  • Not necessarily a stack. You can enter a static field counter, which will fix the index of the returned element of the array. The counter can either increase or decrease, depending on the principle of sampling from the array that you implement. - Serodv
  • Can I take a look at the solution?) - dexploizer

2 answers 2

 class ConnectionManager { private static int MAX_CONNECTIONS = 5; private static Connection[] limitObjects = new Connection[MAX_CONNECTIONS]; private static int counter = 0; static { for (int i = 0; i<MAX_CONNECTIONS; i++) limitObjects[i] = Connection.createNewObject(); } public static Connection getObject() { return counter == MAX_CONNECTIONS ? null : limitObjects[counter++]; } } 
  • Hmm .. as an option. Thank you) - dexploizer
  • @YuriGo, you still need to provide for somehow closing the connections and removing them from the pool. That is, one day you will have a full pool of connections, but some will no longer be needed, but a new one will be needed, then you need to close and delete old ones from the pool, and new ones will be created. For example, before creating a new connection, you can check an array of already created ones and look for closed ones in it. - iksuy

And as an option :)

 class ConnectionManager { private static int MAX_CONNECTIONS = 5; private static ArrayList<Connection> objects = new ArrayList<>(MAX_CONNECTIONS); public static Connection getObject() { if (objects.size() == MAX_CONNECTIONS) { return null; } else { Connection connection = Connection.createNewObject(); objects.add(connection); return connection; } } }