简体   繁体   中英

Create generic array from type specific arrays in Clojure

I am working with JFreeChart in clojure and came across a situation I'd like help.

JFreeChart's DefaultXYDataset has a method addSeries which is used to add series to the chart. The data is supposed to be an array containing two arrays which are type specific(Array of doubles). I therefore wrote the following code thinking it would work but i get a ClassCastException that class [Ljava.lang.Object; cannot be cast to class [[D ([Ljava.lang.Object; and [[D are in module java.base of loader 'bootstrap') class [Ljava.lang.Object; cannot be cast to class [[D ([Ljava.lang.Object; and [[D are in module java.base of loader 'bootstrap') .

(doto _dataset
  (.addSeries "S1" (to-array (conj
                               []
                               (double-array (range 10))
                               (double-array (range 10))))))

After looking through i realized that to-array converts the two nested arrays to #object["[Ljava.lang.Object;" 0x491223e7 "[Ljava.lang.Object;@491223e7"] #object["[Ljava.lang.Object;" 0x491223e7 "[Ljava.lang.Object;@491223e7"] instead of the intended #object["[D" 0x4f5cf37 "[D@4f5cf37"] #object["[D" 0x6d895193 "[D@6d895193"] . Is there a way of combining them to a generic array without converting them to arrays of longs? Maybe another method apart from to-array . Any other suggestions are welcome. Thanks.

Edit: @bfabry answer will work, i could use make-array and then use aset-double but this will result in me looping through the two sequences and assign their values to the main array. I am trying to avoid this as the two datasets can be quite big, even up to 300k items each.

That's two dimensional array, not an array of two array objects. You'll need to use make-array and aset-double to make the array you want.

user=> (class (make-array Double/TYPE 2 2))
[[D

https://clojuredocs.org/clojure.core/make-array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM