http://www.blogjava.net/raylong1982/archive/2007/11/01/157542.html
早上看了java类库中java.util.Arrays 类的toString方法的源代码。如下:(这是JDK1.6的源代码)
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->
public
static
StringtoString(
long
[]a){
if
(a
==
null
)
return
"
null
"
;
int
iMax
=
a.length
-
1
;
if
(iMax
==
-
1
)
return
"
[]
"
;
StringBuilderb
=
new
StringBuilder();
b.append(
'
[
'
);
for
(
int
i
=
0
;;i
++
){
b.append(a[i]);
if
(i
==
iMax)
return
b.append(
'
]
'
).toString();
b.append(
"
,
"
);
}
}
for循环有点奇怪,中间的那个表达式是空的。其实即使加上了条件,for (int i = 0; i<=iMax ; i++) 和源程序是一个效果的,纯粹是多余的,但是我就是多余地加上了这条,结果编译出错了!提示我没有返回语句!
我又重新编写了两个小程序来验证一下:
下面这个能通过编译:
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->
class
Test{
static
Stringm(){
int
a
=
10
;
for
(
int
i
=
0
;;i
++
)
if
(i
==
a
)
return
"
10
"
;
}
public
static
void
main(String[]args){
System.out.println(m());
}
}
for循环的中间语句是空的。
下面这个就不能编译了:
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->
class
Test{
static
Stringm(){
int
a
=
10
;
for
(
int
i
=
0
;i
<=
a;i
++
)
if
(i
==
a
)
return
"
10
"
;
}
public
static
void
main(String[]args){
System.out.println(m());
}
}
其实加上的语句并没有改变原来逻辑结构。这是为什么呢?
如果在for的外面加上一个return语句,随便返回什么字符串,又能通过编译了!!!这个字符串永远不能输出的!!!根本就是个摆设!!!
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->
class
Test{
static
Stringm(){
int
a
=
10
;
for
(
int
i
=
0
;i
<=
a;i
++
)
if
(i
==
a)
return
"
10
"
;
return
"
neverbetouch!!!
"
;
}
public
static
void
main(String[]args){
System.out.println(m());
}
}
另外如果像下面这样在for的中间表达式加上一个恒等式,又能通过编译了!!!这是为什么呢?请高手指点!
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->
class
Test{
static
Stringm(){
int
a
=
10
;
for
(
int
i
=
0
;
true
==
true
;i
++
)
if
(i
==
a
)
return
"
10
"
;
}
public
static
void
main(String[]args){
System.out.println(m());
}
}
附:这是JDK1.5的源码,谢谢GrayWolf!
1.6的代码到底比1.5的改进在哪里呢?我觉得1.5版的实现比较清晰,可读性好一点。
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->
#
public
static
StringtoString(
long
[]a){
#
if
(a
==
null
)
#
return
"
null
"
;
#
if
(a.length
==
0
)
#
return
"
[]
"
;
#
#StringBuilderbuf
=
new
StringBuilder();
#buf.append(
'
[
'
);
#buf.append(a[
0
]);
#
#
for
(
int
i
=
1
;i
<
a.length;i
++
){
#buf.append(
"
,
"
);
#buf.append(a[i]);
#}
#
#buf.append(
"
]
"
);
#
return
buf.toString();
#}