I’m using a singleton for granting a unique copy of each object in runtime:
Car object1= CarFactory.createCar(id);
where the createCar method is:
private static ArrayList<Car> cars= new ArrayList<Car>();
public static synchronized Car createCar(int id){
Car result= new Car(id);
int index= cars.indexOf(result);
if (index==-1){
cars.add(result);
return result;
} else {
return cars.get(index);
}
}
The problem is that with this method each Car have always an reference due to the “cars” collection and the object’s memory is never released. How can I improve it?
Use a
WeakReferenceto wrap the objects before putting them in the list. Example:Note: This is not production code. You will have to build some more safeguards before using it.