Class which can allow to create Only 'n' number of Objects - java

This question is similar to singleton, but i need to create a class that can allow 'n' number of objects only, Below is my code
public class MSInt {
private static MSInt instance = null;
private static int count = 0;
private MSInt()
{
}
public static MSInt getInstance()
{
if(count < 5){
instance = new MSInt();
count++;
return instance;
}
else
{
return null;
}
}
}
This is working but i am thinking a better solution than this if any.

I think this would be a much cleaner way of doing it. You wouldn't need any counters.
Also it looks nice.
import java.util.ArrayList;
public class MSInt {
private static int MAX_OBJS = 10;
private static ArrayList<MSInt> instances = new ArrayList<MSInt>(MAX_OBJS);
private MSInt() {}
public static MSInt mkInstance() {
if(instances.size() < MAX_OBJS){
MSInt obj = new MSInt();
instances.add(obj);
return obj;
} else {
return null;
}
}
public static ArrayList<MSInt> getInstances() {
return instances;
}
}

Your Code is :
private static MSInt instance = null;
this is overwrite methods;
use like this Array :
private static MSInt[] instance = null;
and use a for loop:
for(int i=0;i<5;i++)
{
instance[i] = new MSInt();
return instance[i];
}

I suggest you to use a decorator pattern
so create a class LimitedList<T> extends AbstractList<T> and override add methods in order to check if size is exceeded
I've put code here (gist)

Few suggestions:
replace public static MSInt getInstance() to public static MSInt getInstance(int number). That way you will be able to specify every time what object you are going to get.
Define difference between instances. What attributes does your instances possess? In your example all objects looks the same - it becomes unclear why do you need more than one of them.
Think about initialization. Do you need lazy initialization, or can you initialize all the instances in class initialization. Then you can declare them public static final and deny defining getInstance()
BTW, enum is class that has exactly n instances (by design). It's very likely that defining MSInt as enum will be the most convenient for you.

Using an array or collection means that garbage collection won't remove any of your instances without your knowledge, and it means you can retrieve instances later if required. Using an an MSInt[] might be most practical because it is already capable of making sure only a certain number of objects exist in it. The getInstance() method then loops through the array and if it finds an empty slot, creates a new instances, puts it in the empty spot and returns the result.
public class MSInt {
private static MSInt[] instances = new MSInt[10];
private MSInt(){ }
public synchronized static MSInt getInstance() /*throws TooManyException*/{
for(int i = 0 ; i<instances.length() ; i++){
if(instances[i]==null){
MSInt ms = new MSInt();
instances[i] = ms;
return ms;
}
}
// throw new TooManyException("There are already 10 instances of MSInt");
return null;
}
}
Some exception handling might also be useful. You could throw a custom exception to show that too many instances already exist. Which would make it much more manageable later because you can then define more robust custom behavior for if the array is already full. By removing the comments in the class above and creating the below class, that should work nicely.
public class TooManyException extends Exception {
public TooManyException(String message){
super(message);
}
}
Hope this helps.

Related

How can I make an array of all of the instances of a class?

I want to make an array of all the instances of a class, so that every time a new instance was made, it would automatically be added to the array. How would I do this?
Use a factory pattern. Factory will be the only way to get new instances and therefore can save them in an array.
To show what Zabuza was talking about in an example:
import java.util.ArrayList;
public class Example {
private static ArrayList<Example> collection;
public Example() {
getCollection().add(this);
}
public static ArrayList<Example> getCollection() {
if(collection == null)
collection = new ArrayList<Example>();
return collection;
}
}

Printing a Final Class on the console in json

I am trying to print a final class with static fields on the console, in json format. I am using eclipse.
Stats is a final class that keeps track of object instances that are created or archived. E.g. number of Member instances, number of localities instances etc.
public final class Stats {
public static Integer numMembers = 0;
public static Integer numLocalities = 0;
public static Integer numTowns = 0;
public static void incrementMembers () { numMembers ++; }
public static void incrementLocalities () { numLocalities ++; }
public static void incrementTowns () { numTowns ++; }
}
I ran into problems when I tried to print in json. It does not recognize Stats as an Object instance, which is understandable. Is there a way to print the current state of the Stats class in json?
public static void print () {
System.out.println(GsonBuilder().setPrettyPrinting().create().toJson(Stats));
}
Your current approach will not work with JSON (or any other) serialization, and cannot be made to work the way you want.
A global static object is an anti-pattern as it introduces unwanted coupling into your codebase. There are two approaches to solve this problem, Dependency Injection and Singleton. In both cases, your "statistics" object is a normal object with non-static fields.
public final class Stats {
private int numMembers = 0;
private int numLocalities = 0;
private int numTowns = 0;
public void incrementMembers () { numMembers ++; }
public void incrementLocalities () { numLocalities ++; }
public void incrementTowns () { numTowns ++; }
// Getters...
}
(not sure why you were using Integer, it's not necessary here)
Dependency Injection requires a framework like Spring. If you're not already using Spring then it may be too much change and learning-curve all at one time for you to take on. But it is the best way long-term. An explanation of DI is beyond the scope of an answer here, but the principle is that the framework takes care of instantiating the object and "injecting" it wherever it is needed.
The lighter-weight alternative is the "singleton" pattern (look it up, it is well-documented), where the object contains one static member reference to the single instance that gets created the first time you access it.
public final class Stats {
...
private static Stats instance = null;
public static Stats getInstance()
{
if (instance == null)
instance = new Stats();
return instance;
}
}
(The above is simplistic and ignores threading concerns, study the pattern before using)
Then wherever you need a reference to the (single) Stats instance you do
Stats stats = Stats.getInstance();
In either case you have a real instance that can be serialized.

For what purpose one would want to create a class's instance inside the same class's main?

I came across this kind of example and had difficulty to understand it's actuall purpose:
class YieldDemo extends Thread
{
static boolean finished = false;
static int sum = 0;
public static void main (String [] args)
{
new YieldDemo ().start ();
for (int i = 1; i <= 50000; i++)
{
sum++;
if (args.length == 0)
Thread.yield ();
}
finished = true;
}
public void run ()
{
while (!finished)
System.out.println ("sum = " + sum);
}
}
I've never seen this kind of implementation - why initiating a the new class inside the same class object and not outside the class? is there any particular reason?
In fact you are outside of the class object itself. The main method is a static method, thus it has no dependency on any object instance.
You could also move the main method to any other java file. In general it will also work. However, you need to put static methods in some file. As every java file needs to be a class, you may put the method in the class it works for. For example, the class Math in java is a pure utility class, it has no non-static method.
However, if you create something like this:
public final class Value {
private final int mValue;
public Value(int value) {
mValue = value;
}
public int getValue() {
return mValue;
}
public Value increase() {
return new Value(mValue + 1);
}
}
It can actually make sense if you want Value to be immutable (not change its internal value). So, calling increase() does not increase the value itself but creates a new instance of this object, with an increased value.

Private Constructor initialized by a public method

I came cross a class with private constructor but the object is returned by another public method by call to the private constructor. What may be the advantage of such a construct when we could have made the constructor public?
public final class TokenTable {
static public int errorToken = 0;
static public int timesToken = 1;
static public int divToken = 2;
static public int plusToken = 11;
......
......
private final HashMap<String, Integer> keywordMap = new HashMap();
private final HashMap<String, Integer> operationMap = new HashMap();
private TokenTable() {
operationMap.put("*", timesToken);
operationMap.put("/", divToken);
operationMap.put("+", plusToken);
....
}
static public TokenTable getInstance() {
LexTokenTabInstance = new TokenTable();
return LexTokenTabInstance;
}
}
This is called the Factory pattern. Check out the description here - Factory Design Pattern.
There are several advantages:
you can have multiple named factory methods to create different flavors of the object which can allow for overloading with the same set of parameter types
you can return a singleton if appropriate or maybe return one of a cached set of instances
if don't need to use new
when using generics, the generic type is inferred by the compiler so don't need to use the <> operator
you can return an interface instead of a concrete class
allows for pre-constructor initialization (for example if init must be done prior to calling base class constructor)
To be clear, the above example it seems that it was done just as a "good practice" since none of the above capabilities was used (other than you don't have to use "new").
This is called a factory method. A factory method has many advantages over a constructor:
it has a name (and multiple factory methods may have different names)
it allows returning a cached instance instead of a new instance
it allows returning a subclass instance instead of the actual class
etc.
The main advantage is that no one can create an instance, but using static getInstance method.
This way you can make sure only one instance is created, just as Singelton design pattern
The primary reason for hiding a constructor of a class is to control how objects of that class are created. A common example of this is in the Singleton pattern, where only one object of a class is instantiated.
In order to police this, the user accesses a static method which will access the private constructor if the object isn't created, or else return a reference to the already created object:
public class SingletonDemo {
private static volatile SingletonDemo instance = null;
private SingletonDemo() { }
public static SingletonDemo getInstance() {
if (instance == null) {
synchronized (SingletonDemo.class){
if (instance == null) {
instance = new SingletonDemo();
}
}
}
return instance;
}
}
For other examples, look at Factory patterns in general: http://en.wikipedia.org/wiki/Factory_method_pattern
If you do not want to protect creation of multiple instance outside the class then you can create private constructor.
This is helpful creating a single instance.
You can do it like(Eager loading):
private static final TokenTable tokenTable = new TokenTable();
static public TokenTable getInstance() {
return tokenTable;
}
Or, you can do it like(Lazy loading):
private static TokenTable tokenTable;
static public TokenTable getInstance() {
if(null == tokenTable){
tokenTable = new TokenTable();
}
return tokenTable;
}

java linked list problem

I have written some Java code with 3 simple classes where the first, Controller, has the main method and creates the instances of the other classes. Floaters is a classes that creates a linked list of Floater instances, each with a particular length and boolean value to say if they are vertical or not. My problem, as it says in the commented lines of the first class, is that both "humans" and "otters" Floaters instances are getting assigned the same values and thus have the same size....
Any suggestions on how to fix this?
Thanks in advance!
public class Controller{
private static Floaters humans;
private static Floaters otters;
public static void main(String[] args)
{
otters = new Floaters();
humans = new Floaters();
otters.addFloater(2, true);
otters.addFloater(3, true);
//this should read "2" and it does
System.out.println(otters.size());
//this should read "0" but reads "2". Why?
//How can I get it to read "0"?
System.out.println(humans.size());
}
}
import java.util.LinkedList;
public class Floaters {
private static LinkedList<Floater> llf;
Floaters()
{
llf = new LinkedList<Floater>();
}
public void addFloater(int length, boolean is_vertical)
{
Floater floater = new Floater(is_vertical, (byte)length);
llf.add(floater);
}
public int size()
{
return llf.size();
}
}
public class Floater {
int length;
boolean is_vertical;
Floater(boolean is_vertical, int length)
{
this.length = length;
this.is_vertical = is_vertical;
}
}
The llf in your Floaters-class is static. When you make variables static, they're linked to the class rather than the instance, and thus both instances of Floaters use the same list.
To correct this, simply remove the static from your declaration of the variable.
in floaters, llf should NOT be static
Because of static:
private static LinkedList<Floater> llf;
In this case static means a class field, shared among all instances of a class.
For example - mathematic functions in Java are declared as static metohods of the class java.lang.Math, matemathematical constants are static atributes of this class. So if you use sin(x), you are using always the same method.

Categories