[JAVA-29] facilitate use of "for (X x : collection)" syntax with DBCursor Created: 02/Sep/09 Updated: 02/Oct/09 Resolved: 04/Sep/09 |
|
| Status: | Closed |
| Project: | Java Driver |
| Component/s: | None |
| Affects Version/s: | None |
| Fix Version/s: | 0.9 |
| Type: | Improvement | Priority: | Minor - P4 |
| Reporter: | Jason Sachs | Assignee: | Eliot Horowitz (Inactive) |
| Resolution: | Done | Votes: | 0 |
| Labels: | None | ||
| Remaining Estimate: | Not Specified | ||
| Time Spent: | Not Specified | ||
| Original Estimate: | Not Specified | ||
| Description |
|
Just some food for thought. DBCursor implements Iterator<DBObject> but not Iterable<DBObject> so cannot directly be used in a for loop. Consider implementing Iterable<DBObject> as well, and add its one method perhaps as follows: @Override public Iterator<DBObject> iterator() { This allows the syntax DBCursor cursor = db.find(query); or even for (DBObject object : db.find(query)) It's only a minor convenience over DBCursor cursor = db.find(query); but makes loop code just a bit more clear. I'm getting around this by making my own wrapper class: static public CursorWrapper wrap(DBCursor cursor) { return new CursorWrapper(cursor.copy()); // incoming copy() might not be necessary, but just to be safe }@Override public Iterator<DBObject> iterator() { return this.cursor.copy(); // outgoing copy() might not be necessary, but just to be safe } and then can do for (DBObject obj : CursorWrapper.wrap(coll.find().limit(100))) { System.out.println(obj.get("metadata")); } |