Java String源码解析

简介: public final class String implements java.io.Serializable, Comparable, CharSequence { /** The value is used for character storage.



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;



   先来看几个重要的Properties,首先是value,这个是一个char数组,用来存放字符串用的,这里可以看出来,String实际上使用char数组来实现的。而且这个value定义为private final的,说明是外部不可访问,而且是不可变的。这也是为什么,string类型在使用的时候,定义两个变量进行比较,逻辑上会出现“aaa”!="aaa"的情况了。因为这是后的变量名称,其实也只是一个指向数组的指针。

  接下来就是一堆String的方法,瞅了瞅分成这几类:string的构造方法;String的字符方法;


   有一个要拿出来说说:


/**
     * Returns a canonical representation for the string object.
     * <p>
     * A pool of strings, initially empty, is maintained privately by the
     * class <code>String</code>.
     * <p>
     * When the intern method is invoked, if the pool already contains a
     * string equal to this <code>String</code> object as determined by
     * the {@link #equals(Object)} method, then the string from the pool is
     * returned. Otherwise, this <code>String</code> object is added to the
     * pool and a reference to this <code>String</code> object is returned.
     * <p>
     * It follows that for any two strings <code>s</code> and <code>t</code>,
     * <code>s.intern() == t.intern()</code> is <code>true</code>
     * if and only if <code>s.equals(t)</code> is <code>true</code>.
     * <p>
     * All literal strings and string-valued constant expressions are
     * interned. String literals are defined in section 3.10.5 of the
     * <cite>The Java™ Language Specification</cite>.
     *
     * @return  a string that has the same contents as this string, but is
     *          guaranteed to be from a pool of unique strings.
     */
    public native String intern();


先来个测试:



    intern 这个方法返回的是 返回字符串对象的规范化表示形式,当调用 intern 方法时,如果池已经包含一个等于此 String 对象的字符串(该对象由 equals(Object) 方法确定),则返回池中的字符串。否则,将此 String 对象添加到池中,并且返回此 String 对象的引用。








目录
相关文章
|
6天前
|
Java API 数据库
深入解析:使用JPA进行Java对象关系映射的实践与应用
【4月更文挑战第17天】Java Persistence API (JPA) 是Java EE中的ORM规范,简化数据库操作,让开发者以面向对象方式处理数据,提高效率和代码可读性。它定义了Java对象与数据库表的映射,通过@Entity等注解标记实体类,如User类映射到users表。JPA提供持久化上下文和EntityManager,管理对象生命周期,支持Criteria API和JPQL进行数据库查询。同时,JPA包含事务管理功能,保证数据一致性。使用JPA能降低开发复杂性,但需根据项目需求灵活应用,结合框架如Spring Data JPA,进一步提升开发便捷性。
|
6天前
yolo-world 源码解析(六)(2)
yolo-world 源码解析(六)
16 0
|
6天前
yolo-world 源码解析(六)(1)
yolo-world 源码解析(六)
8 0
|
6天前
yolo-world 源码解析(五)(4)
yolo-world 源码解析(五)
16 0
|
6天前
yolo-world 源码解析(五)(1)
yolo-world 源码解析(五)
29 0
|
6天前
yolo-world 源码解析(二)(2)
yolo-world 源码解析(二)
20 0
|
6天前
Marker 源码解析(二)(3)
Marker 源码解析(二)
10 0
|
6天前
Marker 源码解析(一)(4)
Marker 源码解析(一)
11 0
|
6天前
Marker 源码解析(一)(2)
Marker 源码解析(一)
16 0

推荐镜像

更多