How to make an ArrayList in Clojure
arraylist, clojure, java
Solution
Use `doseq` instead of the lazy `for`. It has for-like bindings but it's meant for side-effects.
(defn make-an-array-list2 []
(let [alist (java.util.ArrayList.)]
(doseq [n (range 6)] (.add alist n)) alist))
;; [0 1 2 3 4 5]
Problem
I need to create and populate an ArrayList in clojure and pass it to an Java API. Can someone help explain why there is a difference in the below two approaches (and why one of them doesn't work). ``` ;;; this works (defn make-an-array-list [] (let [alist (java.util.ArrayList.)] (loop [x 0] (when (< x 6) (.add alist x) (recur (inc x)))) alist)) ;;; ==> [0 1 2 3 4 5] ;;; this does not work (defn make-an-array-list2 [] (let [alist (java.util.ArrayList.)] (for [n (range 6)] (.add alist n)) alist)) ;;; ==> [] ``` Or, any suggestion in stead of the above approach?