Clojure - convert list into Java array

本秂侑毒 提交于 2019-12-12 11:25:05

问题


Is there any idiomatic way of converting Clojure list into Java array, other than first converting it to vector and using into-array (means, something other than (into-array (vec my-list)), as I don't want additional overhead)?


回答1:


Your question seems to be based on a false premise. into-array does not need to take a vector, it takes a seqable value. The documentation ( http://clojuredocs.org/clojure_core/clojure.core/into-array ) contains examples of using into-array on a non-vector sequence:

user=> (into-array (range 4))
#<Integer[] [Ljava.lang.Integer;@63d6dc46>

user=> (type (range 4))
clojure.lang.LazySeq

user=> (doc range)
-------------------------
clojure.core/range
([] [end] [start end] [start end step])
  Returns a lazy seq of nums from start (inclusive) to end
  (exclusive), by step, where start defaults to 0, step to 1, and end
  to infinity.

Calling it on a list works just as well:

user=> (into-array (list 1 2 3))
#<Long[] [Ljava.lang.Long;@138297fe>



回答2:


As I needed to have specifically an integer array, I used int-array function, which takes list as a parameter.



来源:https://stackoverflow.com/questions/16647261/clojure-convert-list-into-java-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!