top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to create fix number of objects in java?

+3 votes
175 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 LinkedIn 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

...