<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Marco Faella on Medium]]></title>
        <description><![CDATA[Stories by Marco Faella on Medium]]></description>
        <link>https://medium.com/@marfaella?source=rss-6fc4df7d714c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pC2KyboO5zY87QxT.</url>
            <title>Stories by Marco Faella on Medium</title>
            <link>https://medium.com/@marfaella?source=rss-6fc4df7d714c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 11:50:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marfaella/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Counting with Java generics]]></title>
            <link>https://medium.com/@marfaella/counting-with-java-generics-ad33c5ef434d?source=rss-6fc4df7d714c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad33c5ef434d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Marco Faella]]></dc:creator>
            <pubDate>Wed, 28 Aug 2019 18:09:35 GMT</pubDate>
            <atom:updated>2020-05-10T08:28:00.379Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s three things that will shock you about Java generics:</p><ol><li>You can encode the length of a list in its type</li><li>You can write a method that accepts two lists at compile time only if they have the same length</li><li>That’s it, really, but “three things” sounds soo much better than “two things”!</li></ol><p>Seriously, consider the following puzzle:</p><blockquote>Can you create a list-like class that exposes its length to the compiler as part of its type?</blockquote><p>This problem would be trivial to solve in C++: just use a <em>non-type template parameter</em>. More precisely, equip the list class with a template parameter of type int (size_t for purists), representing the length of the list. The syntax for doing so is the following:</p><pre>template &lt;class T, int size&gt; class List { ... }</pre><p>Here, T is the type of the objects contained and size is the length of the list. In fact, the C++ class std::array does exactly that.</p><p>Java generics, instead, support <strong>type parameters</strong> only. So, you could say that this article is about emulating integral template parameters in Java.</p><p>To put the puzzle in code, we want a class L such that the following snippet is correct Java and prints the numbers 42, 43, 44:</p><pre>var list1 = new L&lt;&gt;(44);<br>var list2 = list1.add(43); // Head insertion<br>var list3 = list2.add(42);</pre><pre>for (Integer i: list3) {<br>   System.out.println(i);<br>} </pre><p>(I’m using Java 10 type inference for local variables to hide types and create suspense here.)<br>So far, L looks simply like a functional-style immutable sequence of objects,<br>supporting iteration and head-insertion. This mystery class is truly generic — it can contain any kind of objects, not just integers. So, the following is perfectly fine and prints the universal programmer’s greeting:</p><pre>var stringList1 = new L&lt;&gt;(&quot; world!&quot;);<br>var stringList2 = stringList1.add(&quot;Hello,&quot;);</pre><pre>for (String s: stringList2) {<br>   System.out.println(s);<br>}</pre><p>Now comes the tricky part: we want to write a static method sameLength that can only be invoked on two lists <em>of the same length </em>(surprise!) Calling it on different-length lists must raise a <strong>compile-time error</strong>:</p><pre>sameLength(list3, list3); <em>// OK</em><br>sameLength(list1, list3); <em>// Compile-time error!</em></pre><p>Go ahead and try to implement class L. By the way, I should mention that you can do it in a completely type-safe way, in the sense that no cast is involved.<br>Off you go.</p><p>Done?</p><p>Here’s my solution…</p><h3>The basic idea</h3><p>My solution is based on two type parameters: class L&lt;T,N&gt;. The first parameter is the type of the objects contained in the list. In the previous example, both list1 and list2 are subtypes of L&lt;Integer,?&gt;, whereas stringList1 is subtype of L&lt;String,?&gt;.</p><p>The second type parameter is used to expose the length of the sequence,<br>and the trick is … <strong>nesting</strong>!</p><p>The idea is the following:</p><blockquote>If a sequence of length k has type L&lt;T, N&gt;, a sequence of length k+1 has type L&lt;T, L&lt;T, N&gt;&gt;.</blockquote><p>This recursive definition is neat, but it lacks a base case: what’s the type for a sequence of length one? (Assume we avoid empty sequences altogether) That’s L&lt;T, L&lt;T,?&gt; &gt;. I’m using that wildcard to terminate the otherwise endless recursion.</p><h3>Class structure</h3><p>Now, let’s sketch the actual class. It’s a linked list, with a public constructor for clients, and a private constructor used by method add. The second type parameter N (for <em>next</em>) is used as the type of the reference to the next node in the list, which is another object of type L. Hence the bound on N:</p><pre>public class L&lt;T, <strong>N extends L&lt;T,?&gt;</strong>&gt; implements Iterable&lt;T&gt; {<br>   private T item;<br>   private N next;</pre><pre>   public L(T item) {  <em>// Public constructor for the clients</em><br>      this.item = item;<br>   }<br>   private L(T item, N next) {  <em>// Private constructor for add</em><br>      this.item = item;<br>      this.next = next;<br>   }</pre><p>The most interesting bit is the following add method, which extends this list with an extra element:</p><pre>public L&lt;T, L&lt;T,N&gt;&gt; add(T item) {<br>   return new L&lt;&gt;(item, this);    <em>// Tricky line</em><br>}</pre><p>Ponder the tricky line for a second. For it to compile, the this reference must be assignable to the field next of the new object being built. The new object has type L&lt;T,L&lt;T,N&gt;&gt;. So, its next field has type L&lt;T,N&gt;, which is precisely the type of this in add. No problem here.</p><h4>The static method sameLength</h4><p>As promised, you can now write a method that accepts two lists only if they have the same length.</p><p>You just have to:</p><ul><li>State that the two lists accepted by the method have the same type L&lt;T,N&gt;; this ensures that they have the same length.</li><li>Add to the parameter N the constraint that the class L expects.</li></ul><p>You get the following signature:</p><pre>public static &lt;T, N extends L&lt;T, ?&gt;&gt; <br>   void <strong>sameLength</strong>(L&lt;T,N&gt; list1, L&lt;T,N&gt; list2) { ... }</pre><h3>Reminder: bounded type parameters</h3><p>Before we move to more complex scenarios, a quick reminder about the interactions between wildcards and bounded type parameters, like the second parameter in L&lt;T,N&gt;.</p><p>Consider the following fragment:</p><pre>L&lt;Integer,String&gt; withString = null; <strong><em>// Compile-time error</em></strong><br>L&lt;Integer,?&gt; unknown = new L&lt;&gt;();    <em>// Ok, but why?</em></pre><p>The first line is invalid because String doesn’t satisfy the constraint required by L on its second parameter, that is: N extends L&lt;T,?&gt;.</p><p>What about the second line? How is it correct, considering that the wildcard,<br>if interpreted as “unknown type”, is not guaranteed to satisfy that constraint either? The truth is that, in that context, the wildcard implicitly inherits the constraint established by class L. So, L&lt;Integer,?&gt; is really a shorthand for L&lt;Integer, ? extends L&lt;Integer,?&gt;&gt;.</p><p>Try guessing which of the following are correct.</p><p>(In case you’re not familiar with it, Cloneable is a <em>tag interface</em> from the JDK, meaning that it’s an empty interface.)</p><pre>L&lt;Integer,?&gt; reallyUnknown = new L&lt;Integer,?&gt;(0);<br>L&lt;Integer,?&gt; somewhatKnown = new L&lt;Integer,L&lt;Integer,?&gt;&gt;(1);</pre><pre>L&lt;Integer,? extends Cloneable&gt; cloneable1 = null;<br>L&lt;Integer,? super Cloneable&gt;   cloneable2 = null;</pre><h3>Defining an iterator</h3><p>Next, let’s take care of iteration. As for any linked list, we’re going to need a variable pointing to the current node, repeatedly updated with a line like</p><pre>current = current.next;</pre><p>What’s the right type for current? For the moment, call it L&lt;T,something&gt;. To compile the previous line, current.next must be assignable to current, and the type of current.next is “something”.</p><p>So, we have to find a type something that’s assignable to L&lt;T,something&gt;.</p><p>Let’s try a couple of candidates:</p><p>1. something = ?: Definitely too generic. current.next would be assignable only to Object.</p><p>2. something = L&lt;T,?&gt; : Is it assignable to L&lt;T,L&lt;T,?&gt;&gt;?<br>I know, this question hurts my brain too; let’s find a better way to look at it.<br>First, ignore the first type parameter T, because it’s irrelevant for our purposes. Pretend that L comes with a single type parameter, as in</p><pre>class L&lt;N extends L&lt;?&gt;&gt; { … }</pre><p>Now, is L&lt;?&gt; assignable to L&lt;L&lt;?&gt;&gt;? The short answer is no.<br>The long and instructive answer is the following (but I won’t take offense if you skip it).</p><p>The detailed type compatibility rules are complex and take several pages of the language specification, but the high-level principle guiding those rules is simple:</p><blockquote>Every value compatible with the <em>sending type</em> (in this caseL&lt;?&gt;) should be compatible with the <em>receiving type</em> (in this caseL&lt;L&lt;?&gt;&gt;).</blockquote><p>One counter-example is enough to deny assignability, and you can find such a counter-example in this case: Let M be a subclass of L and take an object of type L&lt;M&gt;.<br>Such object is compatible with the sending type, but not with the receiving type, because <em>generic types don’t preserve subtyping </em>(as you know, List&lt;Integer&gt; is not a subtype of List&lt;Number&gt;).</p><p>The following analogy summarises this argument:</p><ul><li>L&lt;M&gt; into L&lt;?&gt;? <strong>Yes.</strong> Like List&lt;ArrayList&gt; fits into List&lt;?&gt;</li><li>L&lt;M&gt; into L&lt;L&lt;?&gt;&gt;? <strong>No.</strong> Like List&lt;ArrayList&gt; <em>doesn’t</em> fit into List&lt;List&lt;?&gt;&gt;</li></ul><p>3. something = ? extends L&lt;T,?&gt;: Yes! Finally, this is the type we need.<br><br>Assuming for simplicity a single-parameter class L&lt;N&gt;, every value compatible with the sending type L&lt;? extends L&lt;?&gt;&gt; is compatible with the receiving type L&lt;L&lt;? extends L&lt;?&gt;&gt;&gt;.</p><p>So, here’s how to implement iteration, using an anonymous class:</p><pre><em>@Override</em><br>public Iterator&lt;T&gt; iterator() {<br>   return new Iterator&lt;&gt;() {<br>      private L&lt;T,? extends L&lt;T,?&gt;&gt; current = L.this; <em>// (*)</em></pre><pre>      public boolean <strong>hasNext</strong>() {<br>         return current != null;<br>      }<br>      public T <strong>next</strong>() {<br>         T result = current.item;<br>         current = current.next;<br>         return result;<br>      }<br>   };<br>}</pre><p>(*) L.thisis the inner-class syntax to name the enclosing object of type L</p><h3>Loose ends</h3><p>If you play with it long enough, you’ll realise this technique has its limits.<br>For example, it doesn’t prevent you from presenting a list as <em>longer</em> than it actually is.</p><p>Here’s how you can declare a list of length one, whose type says “I have length two”:</p><pre>L&lt;Integer,L&lt;Integer,L&lt;Integer,?&gt;&gt;&gt; fake2 = new L&lt;&gt;(42);</pre><p>At this point, you can call sameLength on two lists that actually have different lengths, because they have the same type:</p><pre>sameLength(list2, fake2);   <em>// It compiles. Sad!</em></pre><p>A factory method can prevent that, by fixing the type of the returned object<br>in a way that a constructor cannot do:</p><pre>public static &lt;T&gt; L&lt;T,L&lt;T,?&gt;&gt; <strong>makeNew</strong>(T item) {<br>   return new L&lt;&gt;(item);<br>}</pre><p>If you use the above factory method instead of the constructor, the following attempt is a <strong>compile-time error</strong>:</p><pre>L&lt;Integer,L&lt;Integer,L&lt;Integer,?&gt;&gt;&gt; fake2 = L.makeNew(42);</pre><h3>Applications</h3><p>Why would you want to do something like this? Well, as for all applications of generics, you’re giving more information to the compiler. You’re enlisting the compiler to help you check certain conditions statically.</p><p>For example, in a linear algebra library, you may want to make sure that the <br><a href="https://en.wikipedia.org/wiki/Dot_product">dot product</a> of two vectors is only applied to two equal-length vectors.<br>Normally, you would check this condition at runtime. With the technique presented in this article, you can have <strong>the compiler check it for you</strong>, preventing some potential runtime errors.</p><p>On the other hand, you pay a substantial price:</p><ul><li>The integral type annotation is <em>immutable</em>, you need to create a new object to change it (if it was mutable, the compiler wouldn’t be able to reason about it).<br><br>This constraint is inherent to any compile-time check.<br>It applies equally to proper implementations of non-type parameters, as in C++.</li><li>The resulting type is a <em>mess</em>.<br><br>The emulation trick described in this article generates unreadable types.<br>You really need type inference to be able to work with them, and type inference is not available everywhere. Try writing a method that accepts two L-lists of length 3…<br><br>This drawback is specific to this emulation trick. In C++ you can comfortably write L&lt;Integer,3&gt; instead of <br>L&lt;Integer,L&lt;Integer,L&lt;Integer,L&lt;Integer,?&gt;&gt;&gt;&gt; (yes, that’s 4 times for length 3).</li><li>If you discard the integral type annotation (for example, by accepting a L&lt;T,?&gt;), the compiler loses the ability to reason about it. So, it restricts what you can do with that object. However, this is as much a feature as it is a cost: by hiding the length attribute you get the ability to accept lists of unknown length.<br><br>Notice that you can still check the length at runtime, provided you keep track of it like any normal list does. In fact, it’s a nice exercise to combine this static encoding with the traditional dynamic encoding (that is, storing the list length in a field).<br><br>This issue doesn’t apply to C++, where there are no wildcards and different parametrizations of the same generic class need not have a common supertype.</li></ul><h3>Takeaways</h3><ul><li>Despite erasure, Java generics are more powerful than you may think</li><li>Java generics can emulate integral non-type template parameters</li><li>Non-type parameters allow further checks at compilation time, preventing runtime errors</li><li>Like most emulations, this trick is messy: it generates unreadable types</li></ul><p>Download the source code <a href="https://gist.github.com/mfaella/43c6b36bdb66cc534edf21fa88dacf27">here</a>.</p><p>Use code <em>faella39</em> to get 39% off my book <a href="https://www.manning.com/books/seriously-good-software?a_aid=exercisesinstyle&amp;a_bid=cb63ed89">Seriously Good Software</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad33c5ef434d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>