Destroying objects in Java

后端 未结 8 751
走了就别回头了
走了就别回头了 2021-01-22 00:07

I have a general idea of how the Garbage Collector works in Java, but my reasoning for destroying an object is not because I care about freeing up memory, but because of functio

相关标签:
8条回答
  • 2021-01-22 00:51

    dollar=null will do the trick. By eliminating the reference to that object, the object cannot be referenced. The garbage collector is not relevant here.

    Think about it this way: if you don't want someone to come to your house, you don't have to blow up your house. Just don't give them the address. Fortunately Objects can't stalk other Objects like a crazed ex-girlfriend can stalk the guy who dumped her...parking outside his work, sending texts at all hours, calling his parents...

    Oh, sorry, back to your question.

    If the ground is a Collection of some sort (e.g. a List) then removing that money from your ground collection will also keep it out of the reach of other players or rogue sentient Objects.

    And if your money is also an Object with a value, after picking the first player picks it up you could set its value to -1000, thus punishing the players who would take something that is clearly not theirs.

    0 讨论(0)
  • 2021-01-22 00:51

    Though defining ownership (ground with collection of Moneys, wallet as collection, or owner attribute for money) could be theoretically cleaner solution, I can easily imagine situation when this is overkill.

    For example, it could be completely irrelevant where person have taken his money. And once money have been taken the game don't care who posses that instance of Money

    I suggest to simply add isPicked attribute:

    public class Money {
    
      private final int value;
      private boolean _isPicked = false;
    
      public Money(double x) {
        this.value = x;
      }
    
      public boolean isPicked(){
        return _isPicked;
      }
    
      public void addTo(Person bob) {
        if( this.isPicked )
            throw new Exception("some message for developers");
    
        bob.addToWallet(this.value);
        _isPicked = true;
      }
    
      public static void main(String[] args) {
        Person bob = new Person();
        Money dollar = new Money(1.00);
        dollar.addTo(bob);    // bob finds $1.00
        // dollar = null;     // don't need this anymore
    
        Person alice = new Person();
        dollar.addTo( alice ); // <------   RUNTIME EXCEPTION
      }
    }
    

    Doing dollar = null will result in exception too, but it's less safe, because you can simply forget to do it, or accidentally copy reference to another variable

    0 讨论(0)
提交回复
热议问题