关于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;
  }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理