http://www.javayou.com (收藏,设为首页)
当你不能再拥有时,你唯一能做的,就是让自己不要忘记 (手机请访问 http://3g.dlog.cn/javayou)

一个你可能不知道的简化Java代码的方法

2007年1月2日(Tuesday) 08点58分 作者: Ivan 天气: 心情: 一般

Nat Pryce introduced me to a bit of Java syntax that is simple, useful and suprisingly little used or known.

It was a suprise to find this syntax after so long - I've been writing Java on-and-off for 10 years - it isn't new syntax and I've pair-programmed with people who have written more Java than me who didn't use this syntax - I don't know why it isn't used much more frequently.

The syntax

看看下面这段我们可能经常写的代码:

		ArrayList list = new ArrayList();
		list.add("hello");
		list.add("world");

像上面的代码可以改写为:

		ArrayList list = new ArrayList(){{
			add("hello");
			add("world");
		}};

呵呵,是不是简化很多啊,有意思。

Any talk of neat syntax must mention Smalltalk

但是此种方法仅限于构造函数中,例如下面的代码是不合法的:

		ArrayList list = new ArrayList();
		list{{
			add("hello");
			add("world");
		}};

Keep it simple

In lots of cases, I avoid using language features or syntax that is unusual. However, in this case, I think this syntax is easy to understand and deserves to be more commonly used.

And finally

Sponsor me for the National Autistic Society's London to Paris Bike Ride. OK - so it's not relevant to the article, but they've been very good to me and my autistic son, and my fundraising could do with a boost.

标签: Java 
评论者: Jonney 2007-1-2 09:30 (Tuesday)
呵呵,有意思。
评论者: 219.136.96.* 2007-4-13 23:16 (Friday)
 这个方法好像只对final有效,如果是对象list的或eclipse提示要把对像设成是finall的!
评论者: 刘冬 2007-4-16 10:07 (Monday)
不是这个方法只对final变量有效,是java中所有内嵌的类、方法都只对final有效。
姓名: 
邮箱:  {可选}
网址:  {可选} 此评论只有我和写日记的人查阅
校验码: ... <我看不清楚>
网记为您提供手机和互联网同步的个人主页,带给你不一样的体验