String类引发的联想

  用Find bugs找到了代码中的一处bug

"+".equals (dialNumber.charAt(0))

  原因是charAt()方法返回的是 char类型,char类型比较相等用的是 "=="。正确写法应该是:

'+' == (dialNumber.charAt(0))

  由此想到String类型的比较问题。
  在C/C++中String类型的比较用的是"==",但在Java中String的类型比较却不能用"=="。

  先看看String类的结构(注:下面用的都是JDK1.6的代码,每个版本都有不同)

    /** The value is used for character storage. */
    private final char value[];      //内容

    /** The offset is the first index of the storage that is used. */
    private final int offset;           //偏移量

    /** The count is the number of characters in the String. */
    private final int count;           //长度

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

  在Java中"=="比较的是栈中的值,栈中的存放对象为:函数中基本类型的变量和对象的引用变量、静态类方法。对于String类型来说,栈中存储的是String实例的

引用(既地址)。所以值相同的两个String类实例,地址并不是相同的所以需要调用eauals()方法来判断值是否相等。

  equals()方法的源码如下:

    public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
        char v1[] = value;
        char v2[] = anotherString.value;
        int i = offset;
        int j = anotherString.offset;
        while (n-- != 0) {
            if (v1[i++] != v2[j++])
            return false;
        }
        return true;
        }
    }
    return false;
    }

*花边知识:

1、如何用Eclipse查看JDK源码:http://blog.csdn.net/bruce128/article/details/6887732

2、Java的运算符不同于C/C++不能进行重载,但String可以使用"+"来进行String的连接。这并不是因为重载了"+"运算符,实验可知其实只是通过编译器实现。把   String s = "aa"+"a";进行编译生成.class文件后进行反编译,会发现代码中出现的是String s = "aaa";而不是之前的"+"来连接。

PS:感谢XMG指点!

 

 

 

原文地址:https://www.cnblogs.com/wuchangming/p/2981563.html