探讨"java编程思想(Thinking In Java)"中的一个错误

原文位置:

英文第二版的Holding Your Objects(第九章)--The Arrays class(节) --Comparing arrays(小节):

原文内容:

example
import java.util.*;

public class ComparingArrays {
  public static void main(String[] args) {
    int[] a1 = new int[10];
    int[] a2 = new int[10];
    Arrays.fill(a1, 47);
    Arrays.fill(a2, 47);
    System.out.println(Arrays.equals(a1, a2));
    a2[3] = 11;
    System.out.println(Arrays.equals(a1, a2));
    String[] s1 = new String[5];
    Arrays.fill(s1, "Hi");
    String[] s2 = {"Hi", "Hi", "Hi", "Hi", "Hi"};
    System.out.println(Arrays.equals(s1, s2));
  }
}

Originally, a1 and a2 are exactly equal, so the output is “true,” but then one of the elements is changed so the second line of output is “false.” In the last case, all the elements of s1 point to the same object, but s2 has five unique objects. However, array equality is based on contents (via Object.equals( )) and so the result is “true.”

错误内容:

上面的"but s2 has five unique objects"(中文意思:s2有5个不同的对象)是错误的.其实s2中的只有一个对象,而不是5个,我们可以利用==来测试一下,代码如下:

example
System.out.println(s2[0] == s2[1]);
System.out.println(s2[1] == s2[2]);
System.out.println(s2[2] == s2[3]);
System.out.println(s2[3] == s2[4]);
输出结果:
true
true
true
true

为什么错了呢?我们大家都知道:java中对相同字符串的特殊处理,利用对象池的概念.我们也都知道在java声明字符串可以用两种方法:new和直接赋值(=).

  • 利用new,每次都生成新的对象;
  • 而利用直接赋值,每次VM都在对象池中寻找是否已有此对象,若有,则返回该对象,若没有,再生成新的对象.

对于上面这段规则,想必大家都是很清楚的.若在正常情况下,我们都会注意此类问题,但是在这类稍复杂的情况下(这儿是:把字符串生成放在数组中),我们有时就会犯错误,虽然最后结果是对的.
我是在看中文第二版时发现这个错误的(309页的中间),开始我以为是侯老师翻译错了,后来找来e文对照看,竟然是原作者错了.
后来我又和第三版(英文:改编到了第11章,中文版在306页的开头)对照一下,发现还是错误.

关于此类问题,本书中还有几处,具体位置我记不清了

Note: 注意:String类还有一个特殊方法intern,它的功能就是在对象池中寻找一个相同对象.在一些关键地方,利用这个方法可以提高处理字符串的速度.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值