to-array improvement

3 views
Skip to first unread message

kyle smith

unread,
Aug 19, 2008, 8:22:43 PM8/19/08
to Clojure
(defn to-array [coll class]
(let [x (new ArrayList 0)]
(. x (addAll coll))
(. x toArray (make-array class 0))
))

This is necessary when passing arrays to java methods. This seems
common enough to be part of the language.

Rich Hickey

unread,
Aug 20, 2008, 5:37:47 PM8/20/08
to Clojure
Are you aware of Clojure's to-array and into-array? If so, in what way
is this an enhancement?

Rich

Stuart Sierra

unread,
Aug 21, 2008, 3:47:28 PM8/21/08
to Clojure
I ran into a similar need when passing an array to a method that
expected an array of objects all implementing the same interface.
into-array didn't work because the objects did not share the same
concrete type. But to-array didn't work either, because the type of
the resulting array was wrong. I did this:

(defn to-array-of [class coll]
(let [array (make-array class (count coll))]
(dorun (map (fn [item index] (aset array index item))
coll
(iterate inc 0)))
array))

-Stuart Sierra

kyle smith

unread,
Aug 21, 2008, 9:26:59 PM8/21/08
to Clojure
> > Are you aware of Clojure's to-array and into-array? If so, in what way
> > is this an enhancement?

Well actually, no I wasn't. I found to-array first and didn't think
to look for something else. Perhaps it would be more clear if to-
array was overloaded with a boolean to indicate you want into-array
behavior.
Reply all
Reply to author
Forward
0 new messages