英文第二版的Holding Your Objects(第九章)--The Arrays class(节) --Comparing arrays(小节):
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个,我们可以利用==来测试一下,代码如下:
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和直接赋值(=).
对于上面这段规则,想必大家都是很清楚的.若在正常情况下,我们都会注意此类问题,但是在这类稍复杂的情况下(这儿是:把字符串生成放在数组中),我们有时就会犯错误,虽然最后结果是对的.
我是在看中文第二版时发现这个错误的(309页的中间),开始我以为是侯老师翻译错了,后来找来e文对照看,竟然是原作者错了.
后来我又和第三版(英文:改编到了第11章,中文版在306页的开头)对照一下,发现还是错误.
关于此类问题,本书中还有几处,具体位置我记不清了
Note: 注意:String类还有一个特殊方法intern,它的功能就是在对象池中寻找一个相同对象.在一些关键地方,利用这个方法可以提供处理字符串的速度.
<!-- <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/"> <rdf:Description rdf:about="http://wiki.ebaosh.com/confluence/pages/viewpage.action?pageId=1741" dc:identifier="http://wiki.ebaosh.com/confluence/pages/viewpage.action?pageId=1741" dc:title="探讨"java编程思想"中的一个错误" trackback:ping="http://wiki.ebaosh.com/confluence/rpc/trackback/1741" /> </rdf:RDF> --><!-- Root decorator: all decisions about how a page is to be decorated via the inline decoration begins here. --><!-- Switch based upon the context. However, for now, just delegate to a decorator identified directly by the context. -->