New for Loop 由于许多开发者都希望对于collections和arrays的循环操作能有更紧凑的形式,所以Sun提出了一个新的for语句,包含了foreach的语法含义.
旧语法:void cancelAll(Collection c) { for (Iterator i = c.iterator(); i.hasNext(); ) { TimerTask tt = (TimerTask) i.next(); tt.cancel(); }} 新语法:void cancelAll(Collection c) { for (Object o : c) ((TimerTask)o).cancel();}
void cancelAll(Collection c) { for (Object o = eachof c) ((TimerTask)o).cancel();} 不像foreach, eachof在各种主要的脚本语言中作为要害字使用的并不多,而且对于少数不幸使用了eachof作为方法/变量名的,也有javac ?Csource帮忙.
1.5之前的实现static void eXPurgate(Collection c) { for (Iterator i = c.iterator(); i.hasNext(); ) { String s = (String) i.next(); if(s.length() == 4) i.remove(); }} 1.5+的实现static void expurgate(Collection c) { for (Iterator i = c.iterator(); i.hasNext(); ) if (i.next().length() == 4) i.remove();}
Sun的实现方法void cancelAll(Collection c) { for (TimerTask task : c) task.cancel();} 我提议的方法:void cancelAll((Timertask) Collection c) { for (TimerTask task = eachof c) task.cancel();}
A covariant, or read-only list of Numbers as List<+Number>. A contravariant, or write-only list of Numbers as List<-Number>. A bivariant, read-write list of Numbers as List<*>. An invariant list of Numbers as List<=Number>. 静态安全数组的语法类似.
下面的例子来自variance tutorial,用我所提议的语法结构重写了一次 public abstract class Shape { public abstract void drawOn (Canvas c) }
public class Line extends Shape { public int x, y, x2, y2 public void drawOn (Canvas c) { ... } }
public class Polygon extends Shape { PRivate (Line) List lines; public void drawOn (Canvas c) { ... } }
public class Canvas { public void draw (Shape s) { s.drawOn (this) }
// Covariant (read-only) list of shapes public void drawAll ((Shape..) List shapes) { for (Shape s = eachof shapes) s.drawOn (this) } }
...
// copy from covariant list (read-only) to contravariant list (write-only) public void copy ((Shape..) List from, (..Shape) List to) { for (Shape s = eachof from) to.add (s); }
// copy from covariant array (read-only) to contravariant array (write-only) public void copy ((Shape..)[] from, (..Shape)[] to) { int i = 0; for (Shape s = eachof from) to[i++] = s; }