Count number of a class objects created in JavaIntroduction:In Java, knowing how many objects were created for a specific class is frequently helpful in Monitoring memory usage, keeping track of resource usage, and other performance-related tasks. Problem Statement:The problem is to count the number of objects created for a specific class in Java in an efficient, reliable, and easy-to-use manner. Implementation:Approach 1: Using Static VariableALGORITHM: Step 1: Declare a private static variable called objectCount to store the number of objects created. Step 2: Initialize the objectCount variable to 0. Step 3: Define a constructor that increments the objectCount variable by 1 each time a new object is created. Step 4: Define a static method called getObjectCount() that returns the current value of the objectCount variable. Step 5: Define a finalize() method that decrements the objectCount variable by 1 when an object is destroyed. Step 6: In the main function, create several objects of the class and call the getObjectCount() method to retrieve the current count of objects created. Step 7: Print the count of objects created to the console. FileName: ObjectCounter.java Output: Number of objects created: 3 Complexity Analysis: Time complexity: The time complexity of this algorithm is O(1) because accessing a static variable and calling a static method takes constant time. Space complexity: Because there is only one static variable used to keep track of the object count and because its size is independent of the number of objects created, so the algorithm has an O(1) space complexity. Approach 2: Using Concept of object referencesALGORITHM: Step 1: Create a class-level ArrayList to store the object references. Step 2: In the constructor of the class, add this (the current object reference) to the ArrayList. Step 3: Implement a static method to return the size of the ArrayList, which corresponds to the number of objects created. Step 4: Create objects of the class and call the static method to get the count. FileName: ObjectCounter.java Output: Number of objects created: 3 Complexity Analysis: Time Complexity: Creating objects and calling the static method each time takes linear time O(n), where n is the number of objects created. Space Complexity: The space complexity is O(n), where n is the number of newly produced objects, and the size of the ArrayList increases as objects are created. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India