Java - 将对象设置为空

Java - Setting an object to null

我看到那里有类似的问题,但它们似乎不太适合实际删除对象引用等等。我正在为我正在开发的游戏开发库存系统,并依赖于项目 pickup/swap/put-down 基于插槽是否包含空对象。

这是我的一小段代码:

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;
            }
        }
    }
}

检查工作正常,但是当第一个 if 语句中的代码为 运行 (slots[buttonID].storedItem != null) 时,指定插槽中的对象 'storedItem' 来自该数组未设置为空。如果那里已经有什么东西,我真诚地道歉,但我无法理解外面的人在说什么。

编辑:我修复了它 - 我共享的代码没有任何问题,但我的 MouseListener 的实现存在问题。长话短说,就是被双录了,一拿起就马上放下。

您不需要其中的大部分 if 结构,无论值是否为空,交换都会起作用。假设 0 作为 buttonID 传递,inHand 中存储了一个项目,但插槽 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;
    }
}

我不确定为什么你的代码不能正常工作,看起来它应该可以工作,但显然有一些乍一看看不出来的错误。尝试像这样简化它。不那么冗长的代码往往不太容易出错,因为它更容易管理逻辑。