immutable objects and lazy initialization.

后端 未结 4 1806
悲哀的现实
悲哀的现实 2021-01-20 01:31

http://www.javapractices.com/topic/TopicAction.do?Id=29

Above is the article which i am looking at. Immutable objects greatly simplify your program, since they:

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-20 01:59

    What that line means is, since the object is immutable, then the hashCode has to only be computed once. Further, it doesn't have to be computed when the object is constructed - it only has to be computed when the function is first called. If the object's hashCode is never used then it is never computed. So the hashCode function can look something like this:

    @Override public int hashCode(){
        synchronized (this) {
            if (!this.computedHashCode) {
                this.hashCode = expensiveComputation();
                this.computedHashCode = true;
            }
        }
        return this.hashCode;
    }
    

提交回复
热议问题