zoukankan      html  css  js  c++  java
  • Immutable object

    In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created.[1] This is in contrast to a mutable object, which can be modified after it is created. 

    Immutable objects are often useful because they are inherently thread-safe.[1] Other benefits are that they are simpler to understand and reason about and offer higher security than mutable objects.[1]

    Small immutable objects can easily be copied efficiently, but larger immutable objects require more complicated persistent data structure algorithms to be efficiently copied. Mutable objects are sometimes used instead of immutable objects for performance reasons.

    Python

    In Python, some built-in types (numbers, strings, tuples, frozensets) are immutable, but custom classes are generally mutable. 

    Java

    A classic example of an immutable object is an instance of the Java String class.

    String s = "ABC"; s.toLowerCase();

    The method toLowerCase() will not change the data "ABC" that s contains. Instead, a new String object is instantiated and given the data "abc" during its construction. A reference to this String object is returned by the toLowerCase() method. To make the String s contain the data "abc", a different approach is needed.

    s = s.toLowerCase();

    Now the String s references a new String object that contains "abc". There is nothing in the syntax of the declaration of the class String that enforces it as immutable; rather, none of the String class's methods ever affect the data that a String object contains, thus making it immutable.

     

  • 相关阅读:
    计算公司下班时间(娱乐)
    设计模式-观察者模式
    vue 打包后白屏的问题
    HashSet实现原理
    LinkedList实现原理
    ArrayList的实现原理
    HashMap实现原理分析
    深入理解java动态代理机制
    Spring工作原理
    数据库SQL优化大总结之 百万级数据库优化方案
  • 原文地址:https://www.cnblogs.com/aboutblank/p/2437592.html
Copyright © 2011-2022 走看看