user2973447
user2973447

Reputation: 381

Adding objects from an arraylist to an instance of a class

I have a class called Garden which contains an arraylist of flowers. I have a method which returns an instance of the class in the class and a method to add flowers to the class. How can I add flowers to the instance of the class in my test harness. My code:

public class Garden {

    ArrayList<Flower> flowerbed = new ArrayList<Flower>();
    Hive hive = null;

    private static Garden instance;

    public static Garden getInstance(){
        if(instance == null){
            instance = new Garden();
        }
        return instance;
    }

    public void addFlower(Flower flower){
        flowerbed.add(flower);
    }//some methods omitted
}

If I do:

Flower f;
Garden g = new Garden();
g.addFlower(f);

a new flower is added to the garden but not to the instance of the garden and because the getInstance method is static it is confusing me on how to use it in my testharness.

Upvotes: 0

Views: 895

Answers (2)

robbmj
robbmj

Reputation: 16516

Garden.getInstance().addFlower(new Flower());
Garden.getInstance().addFlower(new Flower());

you are using the singleton pattern so you should make Garden's constructor private

private Garden() {}

Also since there is no reason to subclass a singleton

public final class Garden

calling getInstance of garden will always return the same instance of Garden no matter who calls it.

Also you want to make sure flowerBed is not static, like you have.

private Arraylist<Flower> flowerBed = new ArrayList<>();

Upvotes: 2

csvan
csvan

Reputation: 9454

I might have misunderstood your question since the answer seems all too trivial, but to add flowers to the class you should simply use the addFlower method you already provided.

 public void testMethod() {

     Flower one = new Flower();
     Flower two = new Flower();

     Garden garden = Garden.getInstance();
     garden.addFlower(one);
     garden.addFlower(two);
 }

EDIT: As pointed out by Robbmjs answer, to properly apply the singleton pattern your constructor(s) for Garden should be private.

Upvotes: 1

Related Questions