乐趣区

关于java:String-为什么是-final

源码现状

浏览源码能够发现,String 被 final 润饰,其 value 变量也被 final 润饰,这是 2 件事;
首先,String 类被 final 润饰,类不能够被继承。躲避了有人想尝试通过继承重写来毁坏 String 外部的数据;
其次,外部成员变量 char value[] 被 final 润饰,value 援用地址不可变;

起因可分为

平安

1. 应用平安,String 是最罕用的对象,不可变躲避了间接在堆中间接扭转对象内容,除非被动批改援用地址,否则咱们将 String 传递进任何办法中,他都不会扭转,避免一不小心就在其余函数内被更改了;
2. 线程平安,并发应用 String 时,不须要再去思考他的线程平安问题;

性能

1. 字符串缓冲池,应用享元模式,缩小 String 对象的产生,而享元模式的弊病就是对象的外部状态不可变;
2.hash 算法,因为 String 初始化就不可变,所以一个 String 的 hashcode 是固定的不变的,能够只计算一次,并且 String 是最适宜作为 hashMap 中的 Key;

public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
  /** The value is used for character storage. */
  private final char value[];

  /** Cache the hash code for the string */
  private int hash; // Default to 0

  /** use serialVersionUID from JDK 1.0.2 for interoperability */
  private static final long serialVersionUID = -6849794470754667710L;

  /**
   * Class String is special cased within the Serialization Stream Protocol.
   *
   * A String instance is written into an ObjectOutputStream according to
   * <a href="{@docRoot}/../platform/serialization/spec/output.html">
   * Object Serialization Specification, Section 6.2, "Stream Elements"</a>
   */
  private static final ObjectStreamField[] serialPersistentFields =
      new ObjectStreamField[0];

  /**
   * Initializes a newly created {@code String} object so that it represents
   * an empty character sequence.  Note that use of this constructor is
   * unnecessary since Strings are immutable.
   */
  public String() {this.value = "".value;}

  /**
   * Initializes a newly created {@code String} object so that it represents
   * the same sequence of characters as the argument; in other words, the
   * newly created string is a copy of the argument string. Unless an
   * explicit copy of {@code original} is needed, use of this constructor is
   * unnecessary since Strings are immutable.
   *
   * @param  original
   *         A {@code String}
   */
  public String(String original) {
      this.value = original.value;
      this.hash = original.hash;
  }
}
退出移动版