Carl Litchman
Carl Litchman

Reputation: 129

Java - Setting an object to null

I've seen that there are questions similar to this out there, but they seem rather niche to actually deleting the object reference and whatnot. I'm working on an inventory system for a game I'm working on, and rely on item pickup/swap/put-down based on wether a slot contains a null object or not.

Here's my little bit of code:

public void buttonPressed(int buttonID) {
    if(buttonID < slots.length) {
        if(inHand == null) {
            if(slots[buttonID].storedItem != null) {
                inHand = slots[buttonID].storedItem;
                slots[buttonID].storedItem = null;
            }
        } else {
            if(slots[buttonID].storedItem == null) {
                slots[buttonID].storedItem = inHand;
                inHand = null;
            } else {
                Item swapSpot = inHand;
                inHand = slots[buttonID].storedItem;
                slots[buttonID].storedItem = swapSpot;
            }
        }
    }
}

The checks are working correctly, but when the code in the first if statement is run (slots[buttonID].storedItem != null), the Object 'storedItem' in the specified slot from the array is not being set to null. I sincerely apologize if there's something already out there, but I can't wrap my head around what people out there are saying.

Edit: I fixed it - nothing was wrong with the code I shared, but there was an issue with the implementation of my MouseListener. Long story short, it was being double-registered, and as soon as you picked up an item, it would be put back down instantly.

Upvotes: 0

Views: 1285

Answers (1)

Imred_Gemu
Imred_Gemu

Reputation: 58

You don't need most of that if structure, the swap will work whether the values are null or not. Lets assume 0 was passed as the buttonID, there is an item stored in inHand, but no item in slot 0.

public void buttonPressed(int buttonID) {
    if(buttonID < slots.length) {
        //The item in inHand is now placed into swapSpot
        Item swapSpot = inHand;
        //The null value in slots[buttonID].storedItem is now placed in inHand
        inHand = slots[buttonID].storedItem;
        //The item previously in inHand is now placed in slots[buttonID].storedItem
        slots[buttonID].storedItem = swapSpot;
    }
}

I'm not sure why your code doesn't work right, it looks like it should work, but obviously there's something wrong that isn't visible at first glance. Try simplifying it like this. Code which is less verbose tends to be less error prone as it is easier to manage the logic.

Upvotes: 2

Related Questions