<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Clojure Q&amp;A - Recent questions tagged assoc</title>
<link>https://ask.clojure.org/index.php/tag/assoc</link>
<description>Powered by Question2Answer</description>
<item>
<title>assoc with a negative index on a subvec doesn&#039;t throw and writes before the subvec&#039;s start</title>
<link>https://ask.clojure.org/index.php/15308/assoc-negative-index-subvec-doesnt-throw-writes-before-subvecs</link>
<description>&lt;p&gt;Clojure 1.12.7, JDK 21 (same in 1.11.4 and on master).&lt;/p&gt;
&lt;p&gt;Calling &lt;code&gt;assoc&lt;/code&gt; on a &lt;code&gt;subvec&lt;/code&gt; with a negative index (from &lt;code&gt;-start&lt;/code&gt; to -1) returns normally and writes to the backing vector before the subvec&#039;s start.&lt;/p&gt;
&lt;p&gt;Expected: &lt;code&gt;IndexOutOfBoundsException&lt;/code&gt;, the same as &lt;code&gt;assoc&lt;/code&gt; on a regular vector.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(assoc [2 3] -1 :x)
;; =&amp;gt; IndexOutOfBoundsException

(def sv (subvec [0 1 2 3 4] 2 4))
(let [s (assoc sv -1 :x)]
  [s (.-v s) (= s sv)])
;; Actual: [[2 3] [0 :x 2 3 4] true]
;; Expected: IndexOutOfBoundsException
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;assoc-in&lt;/code&gt;, &lt;code&gt;update&lt;/code&gt;, and a &lt;code&gt;subvec&lt;/code&gt; of &lt;code&gt;vector-of&lt;/code&gt; behave the same. A subvec starting at 0 or an index below &lt;code&gt;-start&lt;/code&gt; throws from the backing vector.&lt;/p&gt;
&lt;p&gt;Cause: &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/clojure/clojure/blob/clojure-1.12.7/src/jvm/clojure/lang/APersistentVector.java#L661-L667&quot;&gt;SubVector.assocN&lt;/a&gt; checks only &lt;code&gt;start + i &amp;gt; end&lt;/code&gt; and omits the &lt;code&gt;i &amp;lt; 0&lt;/code&gt; check that &lt;a rel=&quot;nofollow&quot; href=&quot;https://clojure.atlassian.net/browse/CLJ-962&quot;&gt;CLJ-962&lt;/a&gt; added to &lt;code&gt;SubVector.nth&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;This bug is reported at &lt;a rel=&quot;nofollow&quot; href=&quot;https://s.conao3.com/blog/2026/e4f733&quot;&gt;https://s.conao3.com/blog/2026/e4f733&lt;/a&gt;&lt;/p&gt;
</description>
<category>Collections</category>
<guid isPermaLink="true">https://ask.clojure.org/index.php/15308/assoc-negative-index-subvec-doesnt-throw-writes-before-subvecs</guid>
<pubDate>Thu, 03 Dec 2026 19:17:29 +0000</pubDate>
</item>
</channel>
</rss>