0

Which Clojure methods can I use to create multiple instances on an object and store then in an Java ArrayList?

I know how to do this in Java but I'm not sure how to proceed in Clojure, any help/pointers will be much appreciated

0

2 Answers 2

1

Look at http://clojure.org/java_interop

(doto (new java.util.ArrayList) 
    (.add (new Object)) 
    (.add (new Object))) 

returns #<ArrayList [java.lang.Object@5ae7fa2, java.lang.Object@33d6798]>

There are 2 forms for creating new objects in clojure.

(Classname. args*)
(new Classname args*)

So here is the straightforward example how to create the java object in clojure. Firstly how it looks in Java:

Thread thread = new Thread("Hi there");

Clojure

; return instance of java.lang.Thread class
(new Thread "Hi there")

or another way

(Thread. "Hi there")
Sign up to request clarification or add additional context in comments.

5 Comments

thanks I know how to work with arraylists but I dont know how to create an object and store them in an arraylist, if that makes sense
@RicardoSanchez The code in hsestupin's answer does create two objects and stores them in the array list.
@RicardoSanchez Sorry, i dont udnerstand what do u mean
Ok what I dont know how to do is to create an Object I would like to know how to do it in Clojure
@RicardoSanchez It's right there in the code: (new Object). That's how you create an object.
0

why not store in vector?

user=> (def lst (atom []))
user=> (swap! lst conj "String")
user=> (swap! lst conj 123)
user=> @lst
["String" 123]

2 Comments

So lst is like a C++ struct?
@RicardoSanchez No, lst is an atom containing a vector. An atom is (kinda, sorta) like a pointer in C++ and a vector is like a const vector in C++. So what this code does in C++ terms is: it creates a non-const pointer called lst pointing to a const empty vector. Then it creates a const vector containg the string "String" and makes lst point to that. Then it creates a const vector containing "String" and 123 and makes lst point to that. Then it dereferences the pointer. Note that this is not how you usually do things in Clojure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.