Topic: 請教一個小問題(new String[0] 數組有什麼用)

  Print this page

1.請教一個小問題(new String[0] 數組有什麼用) Copy to clipboard
Posted by: winterlord
Posted on: 2005-08-15 09:46

请使用准确的文字描述作为标题
Your next post without a proper Subject will be removed.

Where do you find this?



new String[0]
請問定義一個長度為零的數組有什麼用??能舉個例子嚜?

2.Re:請教一個小問題(new String[0] 數組有什麼用) [Re: winterlord] Copy to clipboard
Posted by: winterlord
Posted on: 2005-08-15 10:56

是在java類庫 java.nio.charset中看到的,
定義一個空數組,但是不明白這樣做的意義


protected Charset(String canonicalName, String[] aliases) {
  checkName(canonicalName);
  String[] as = (aliases == null) ? new String[0] : aliases;
  for (int i = 0; i < as.length; i++)
   checkName(as[i]);
  this.name = canonicalName;
  this.aliases = as;
}

3.Re:請教一個小問題(new String[0] 數組有什麼用) [Re: winterlord] Copy to clipboard
Posted by: bluepure
Posted on: 2005-08-15 11:10

减少对数组的nullpointExcetption的捕获.和null判断,少写冗余无用的代码

比如:

方法 a

如下两种写法

public Object[] a{
//do something
return null;
}



public Object[] a{
//do something
return new Object[0];
}


方法 b来调用:

Object[] var= a();

for (int i = 0; i < var.length; i++) {
System.out.println(var[i]);
}

而你如果不能够保证a方法返回的一定是没有null的,就必须写成:


Object[] var= a();
if(var!=null){
for (int i = 0; i < var.length; i++) {
System.out.println(var[i]);
}
}


或者

try {
Object[] var= a();
for (int i = 0; i < var.length; i++) {
System.out.println(var[i]);
}
}
catch (NullPointerException ex) {
//无谓的代码
}


详细参考 《Effective java》

4.Re:請教一個小問題(new String[0] 數組有什麼用) [Re: winterlord] Copy to clipboard
Posted by: winterlord
Posted on: 2005-08-15 11:41

喔,明白了,謝謝


   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