[armedbear-devel] Java Collections, ABCL, and you

Rudolf Schlatte rudi at constantly.at
Sat Feb 4 21:41:53 UTC 2012


Hi,

Here are my unordered thoughts about the same topic.  Executive summary: trying to shoe-horn iterators into the CL sequence API in a useful way seems quite hopeless to me, but transparent access to Java vectors and arrays would be neat (but less useful since not many Java APIs hand these out, preferring to give you iterators).

There are two things I might like to do with a Java collection: iterating through it myself, and passing it to some 3rd-party Lisp library.  Note that there are more things I might want to do with Java arrays, vectors and other array-likes.


* Iterating through a collection myself

The following fragment does this to my satisfaction:

(loop with iterator = (#"iterator" (#"getEdges" object-graph))
     while (#"hasNext" iterator)
     do (progn (#"removeEdge" object-graph (#"next" iterator))))

This is not more verbose than any other extended loop usage.  (As Alessio explains, anything more fancy cannot be done in a completely generic way, because various Java datatypes have different semantics wrt random access, read-onlyness, etc).  Note that CL itself has a similar problem, hence maphash, dolist, etc.

For user convenience, we could introduce a loop path for iterators, something like:

(loop for x being each element in (#"getIterator" foo) do (frob x))


* Passing Java iterators / sequences to code not knowing about Java iterators

In general, this will be hairy, but for not-too-large amounts of data I think a Lisp-side equivalence of LispObject.copyToArray() should do the trick, as long as mutating the sequence is not supposed to alter the Java-side data structure.  Untested:

(defun vectorify (iterator)
  (coerce (loop while (#"hasNext" iterator) collect (#"next" iterator)) 'vector))

The result can be passed to any

* Java arrays, Vector, ArrayList and friends

These have semantics sufficiently similar to CL's sequences (random access, settable) that the existing sequence protocol should suffice.


Rudi





More information about the armedbear-devel mailing list