Sets the value at the index/indices. Works on Java arrays of reference types. Returns val.
user=> (def my-array (into-array Integer/TYPE [1 2 3])) #'user/my-array user=> (aset my-array 1 10) ; Set the element with index 1 to 10 10 user=> (into [] my-array) [1 10 3]
; Two dimensional example (use 'clojure.pprint) (let [the-array (make-array Long/TYPE 2 3) ] (dotimes [nn 6] (let [ii (quot nn 3) jj (rem nn 3) ] (aset the-array ii jj nn) )) (pprint the-array) ) ;=> [[0, 1, 2], [3, 4, 5]] ; Types are defined in clojure/genclass.clj: ; Boolean/TYPE ; Character/TYPE ; Byte/TYPE ; Short/TYPE ; Integer/TYPE ; Long/TYPE ; Float/TYPE ; Double/TYPE ; Void/TYPE
;; Simple 2D example: (def a (to-array-2d [[1 2] [3 4]])) ;=> #'expt.core/a (aset a 0 1 "foo") ;=> "foo" expt.core=> (map vec a) ;=> ([1 "foo"] [3 4])
;; transpose a matrix (two-dimensional array of doubles) ;; using in-place mutation and no additional memory space. (defn transpose! [^"[[D" matrix] (dotimes [i (alength matrix)] (doseq [j (range (inc i) (alength matrix))] (let [copy (aget matrix i j)] (aset matrix i j (aget matrix j i)) (aset matrix j i copy))))) (def matrix (into-array (map double-array [[1.0 2.0 3.0] [4.0 5.0 6.0] [7.0 8.0 9.0]]))) (transpose! matrix) (mapv vec matrix) ;; [[1.0 4.0 7.0] ;; [2.0 5.0 8.0] ;; [3.0 6.0 9.0]]
;; Doubles are converted to floats; longs to ints, and vice versa: (aset (int-array [1 2 3]) 0 (long 42)) ;; => 42 (aset (long-array [1 2 3]) 0 (int 42)) ;; => 42 (aset (float-array [1.0 2.0 3.0]) 0 (double 42.0)) ;; => 42.0 (aset (double-array [1.0 2.0 3.0]) 0 (float 42.0)) ;; => 42.0 ;; But some other conversions that may seem possible, are not: (aset (byte-array [1 2 3]) 0 (int 42)) ;; => Execution error (IllegalArgumentException) at… ;; No matching method aset found taking 3 args (aset (short-array [1 2 3]) 0 (long 42)) ;; => Execution error (IllegalArgumentException) at… ;; No matching method aset found taking 3 args ;; It's best to be explicit: (aset (short-array [1 2 3]) 0 (short 42)) ;; => 42
aset