java - 如何通过仅在数组中引用来使对象为空?

标签 java arrays object reference null

我在 GameWorld 中有一系列游戏对象,它们可以从那个世界中移除。问题是某些游戏对象引用了其他游戏对象。例如。 Player 类有一个对 Bird 的引用。 Bird 被随机从 GameWorld 中移除,但 Player 仍然有对它的引用。我目前做一个空检查来检查游戏对象是否仍然有效并且在世界上。但是,从数组中删除对象不会使该引用为空。那么我怎样才能让它为空呢?

这是一个例子:

// GameWorld creates bird
ArrayList<Object> gameObjects = new ArrayList<>();
Object bird = new Object();
gameObjects.add(bird);

// Player references it
Object referencedBird = gameObjects.get(0);

// later in GameWorld, another scope, there is no access to the 'bird' object, trying to remove the bird from the world
Object objectToRemove = gameObjects.get(0);
gameObjects.remove(0);
objectToRemove = null;

// back in the Player class
Debug.log("is null " + (referencedBird == null)); // false! I need it to be true

最佳答案

你不能让一个对象null,你只能让一个引用null。更新对对象的一个​​引用不会更改对同一对象的其他引用。

想一想我们的手机中都有同一个人的号码:如果我删除该号码,它不会从您的手机中删除。如果我们都删除它,那个人的电话号码不会不复存在:只是我们都不能调用他们。

你唯一能做的是:

  • 明确设置referencedBird = null
  • 或者通过 gameObjects.get(0) 而不是通过 referencedBird 变量来引用它。

关于java - 如何通过仅在数组中引用来使对象为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38570436/

相关文章:

python - 将 lambda 表达式应用于数组元素时出现 ValueError

java - 在java中对相关文本文件进行排序创建公共(public)索引

javascript - 根据属性值从对象数组中获取值

java调用其他类中的方法无法识别更改的变量

php - 将复选框 PHP 表单项作为数组插入到 MySQL 数据库

java - Android 程序中 onCreate() 中的 NullPointerException

c - 结构C的矩阵

javascript - 使用转换器解构对象

java - 如何在 Java 中使类可变

java - 如何在 Spring Boot 应用程序中添加两个上下文路径