Topic: 这样的数组有什么区别?

  Print this page

1.这样的数组有什么区别? Copy to clipboard
Posted by: wu_Java1981
Posted on: 2006-07-31 14:45

请教一下,下面两个数组定义有什么区别?
String[] str1 = {'1','2','3','4',}; //这个有个逗号
String[] str2 = {'1','2','3','4'}; //这个没有逗号
这样定义的数组长度都一样,都本人不知道有什么区别或说本人认为str1的定义是错的。
请指教,谢谢!

2.Re:这样的数组有什么区别? [Re: wu_Java1981] Copy to clipboard
Posted by: why
Posted on: 2006-07-31 19:49

沒区别
但都是错的:
String[] str2 = {"1","2","3","4"};
char[] str2 = {'1','2','3','4'};

3.Re:这样的数组有什么区别? [Re: wu_Java1981] Copy to clipboard
Posted by: 铁针
Posted on: 2006-08-01 10:44

是把“书”上的代码照搬来的呢还是楼主自己想出来这么写的呢?

4.Re:这样的数组有什么区别? [Re: 铁针] Copy to clipboard
Posted by: zcjl
Posted on: 2006-08-01 10:42

奇怪,应该是不符合语法的代码,编译却不会出错,编译器的容错性真不赖啊
String[] strs = {"1", "2", "3", };
System.out.println(strs.length);

5.Re:这样的数组有什么区别? [Re: zcjl] Copy to clipboard
Posted by: why
Posted on: 2006-08-01 12:29

zcjl wrote:
奇怪,应该是不符合语法的代码,编译却不会出错,编译器的容错性真不赖啊
String[] strs = {"1", "2", "3", };
System.out.println(strs.length);

是符合语法的

ArrayInitializer:
{ [VariableInitializer {, VariableInitializer} [,]] }

VariableInitializer:
ArrayInitializer
Expression

http://java.sun.com/docs/books/jls/third_edition/html/syntax.html#18.1

6.Re:这样的数组有什么区别? [Re: wu_Java1981] Copy to clipboard
Posted by: wu_Java1981
Posted on: 2006-08-01 22:20

谢谢问题儿童。
这是我写错了,不符合语法,我只是想问问这两种写法的区别,初学者难免会出错,望谅解!

7.Re:这样的数组有什么区别? [Re: wu_Java1981] Copy to clipboard
Posted by: why
Posted on: 2006-08-01 23:14

wu_Java1981 wrote:
我只是想问问这两种写法的区别,初学者难免会出错,望谅解!

沒区别

倒想知道閣下為何會有此一問。

8.Re:这样的数组有什么区别? [Re: wu_Java1981] Copy to clipboard
Posted by: wu_Java1981
Posted on: 2006-08-03 20:36

Answer(问题儿童):
String[] str1 = {"1","2","3","4",}; //这个有个逗号
String[] str2 = {"1","2","3","4"}; //这个没有逗号
有逗号的,我认为好像有些错误,我认为逗号后面还应该跟着,还没完。。。
所以就这么问了。

9.Re:这样的数组有什么区别? [Re: wu_Java1981] Copy to clipboard
Posted by: floater
Posted on: 2006-08-05 05:27

This is good for quick testing. I always use this. In my case, I have a table, sometimes I care some columns, other times I care some other columns, so I am lazy to remove the last comma when I change columns. It's convenient.

10.Re:这样的数组有什么区别? [Re: wu_Java1981] Copy to clipboard
Posted by: awrong
Posted on: 2006-08-19 22:11

String[] str1 = {'1','2','3','4',}; 编译会出错呀,提示类型不配,一个是char,一个是String,怎么不会出错的???
当然,不嫌麻烦你可以用valueOf()方法,将它转成String类型,如String[] str1 = {String.valueOf(1),String.valueOf(2),String.valueOf(3),String.valueOf(4)}; 哈哈,你说累不累呀。。。。。。
String[] str1 = {"1","2","3","4",}; 多一个“,”不出错,其长度还是4,但再加一个“,”,编译出错,提示语法错误,呵呵。


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923