Declaring Variables as static: Unexpected behaviour

I am developing a Java Spring project that uses Spring data.

It uses repositories to remove Dog Objects from a Kennel Object when the dog is collected by its owner.

Note that there can be multiple dogs associated with the one Kennel. There are also many kennels.

I have declared all my variables and methods as Static.

E.g:

static Kennel kennel;

dogsWithReleasedStatus;

static List<Dog> dogsWithReleasedStatus = new ArrayList<Dog>();

static List<Dog> allDogsInKennel = new ArrayList<Dog>();

Remove Method:

public static void removeDogFromKennel(int dogInKennel, List<Dog> allDogsInKennel) {
        //Loop through all dogs in the Kennel
        for (dogInKennel = 0; dogInKennel < allDogsInKennel.size(); dogInKennel++) {

            if (allDogsInKennel.get(dogInKennel).getStatus() == dogStatus.RELEASED) {

                kennel.removeDog(allDogsInKennel.get(dogInKennel));

                dogInKennel--;


            }
        }
    }

Calling remove method in the main:

(note getAllKennelIds() just returns a list of kennel Ids as strings ):

List<String> kennelIdsToloopThrough = getAllKennelIds();

 for (int i = 0; i < kennelIdsToloopThrough.size(); i++) {

 //create list with all dogs in kennels 
 allDogsInKennel = kennel.getDogsList();

 //pass list and remove dog from kennel if status = released
 removeDogFromKennel(i,allDogsInKennel);

 //save the changes to the DB
 kennelRepository.save(kennel);

 }

The issue I am having is that when the save method is called, it is deleting ALL the dogs in kennels, not just those with a "released" status.

What am I doing wrong?

Jon Skeet
people
quotationmark

Note that there can be multiple dogs associated with the one Kennel. There are also many kennels.

Currently there is nothing associated with an individual Kennel. The fact that all your variables are static means that they are associated with the Kennel type rather than with a specific instance of the type.

Fundamentally, you need to work out what information is specific to an individual kennel (such as the dogs within it) - and those fields should not be static.

You should read the "Understanding Class Members" tutorial (or a good Java book) for more information about the difference between static fields and instance fields.

I would additionally strongly advise you to put away Spring, databases etc and just experiment with the basics of the language before you go any further.

people

See more on this question at Stackoverflow