日期:2014-05-16 浏览次数:20412 次
public List getUsers() { ResultSet rs = userDbQuery(); List retval = new ArrayList(); while (rs.next()) { retval.add(rs.getString(1)); } return retval; }上面是个我们采取返回Collection后最常用的方法,将ResultSet中的用户名加入List再返回,显然这很耗费内存。
public Iterator getUsers() { final ResultSet rs = userDbQuery(); return new Iterator() { private Object next; public void hasNext() { if (next == null) { if (! rs.next()) { return false; } next = rs.getString(1); } return true; } public Object next() { if (! hasNext()) { throw new NoSuchElementException(); } String retval = next; next = null; return retval; } public void remove() { throw new UnsupportedOperationException("no remove allowed"); } } }
public Iterator getUsers() { ResultSet rs = userDbQuery(); List list = new ArrayList() while (rs.next()) { list.add(rs.getString(1)); } return list.iterator(); }