top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

How to create fix number of objects in java?

+3 votes
22 views
How to create fix number of objects in java?
posted Sep 22, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

0 votes

You could add a static counter to the class, and when it reaches the maximum count you can throw an exception in the constructor.

Or you can use a Singleton pattern. It is typically used to restrict the number of objects created by a class to one, but it could be used just as well to restrict the number object created by the class to any other amount.

SAMPLE:

public class Example
{
  private Example()
  {
  }
 private static Example obj[3];
 Static int i=0;

 public static Example  getInstance()
 {

        if((i<3)&&(obj[i]==null))
         {
          obj[i]=new Example();
           return obj[i++];
         }
         else{
                if(i==3)
                   i--;
                 return obj[i];
                }
   }
answer Apr 19, 2016 by Karthick.c
Similar Questions
+4 votes

Design an algorithm to accept a string from the user. Count and print the number of times each character occurs in the given string. Example –
input string = "malayalam"
Output must be –
m – 2
a – 4
l – 2
y - 1

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...