<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Umair&#039;s Blog &#187; Java</title>
	<atom:link href="http://umairsaeed.com/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://umairsaeed.com</link>
	<description></description>
	<lastBuildDate>Fri, 20 Jan 2012 16:28:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='umairsaeed.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Umair&#039;s Blog &#187; Java</title>
		<link>http://umairsaeed.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://umairsaeed.com/osd.xml" title="Umair&#039;s Blog" />
	<atom:link rel='hub' href='http://umairsaeed.com/?pushpress=hub'/>
		<item>
		<title>Finding the Start of a Loop in a Circular Linked List</title>
		<link>http://umairsaeed.com/2011/06/23/finding-the-start-of-a-loop-in-a-circular-linked-list/</link>
		<comments>http://umairsaeed.com/2011/06/23/finding-the-start-of-a-loop-in-a-circular-linked-list/#comments</comments>
		<pubDate>Thu, 23 Jun 2011 13:54:07 +0000</pubDate>
		<dc:creator>Umair</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Algos]]></category>

		<guid isPermaLink="false">https://umairsd.wordpress.com/?p=186</guid>
		<description><![CDATA[A lot of people are familiar with the problem of detecting a loop in a linked list. The problem goes as follows: “Given a linked list, what is the algorithm to determine if it has any cycles (loops)?” The algorithm &#8230; <a href="http://umairsaeed.com/2011/06/23/finding-the-start-of-a-loop-in-a-circular-linked-list/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&amp;blog=9333327&amp;post=186&amp;subd=umairsd&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A lot of people are familiar with the problem of detecting a loop in a linked list. The problem goes as follows: “Given a linked list, what is the algorithm to determine if it has any cycles (loops)?”</p>
<p>The algorithm is pretty straightforward:</p>
<ol>
<li>We start at the beginning of the linked list with two pointers.</li>
<li>The first pointer is incremented through each node of the list. The second pointer moves twice as fast, and skips every other node.</li>
<li>If the linked list contains a loop, these two pointers will eventually meet at the same node, thus indicating that the linked list contains a loop.</li>
</ol>
<p>The algorithm is straightforward and it is relatively easy to create a mental model and get an intuitive sense of why it works.</p>
<p>Now, a slight twist to the same question asks: “Given a circular linked list, what is the algorithm to find the first node of the loop.” For instance, in the circular list A-&gt;B-&gt;C-&gt;D-&gt;E-&gt;C, the first node of the loop is node C. The first part of the algorithm is identical to the algorithm for finding if there is a loop (above). Once a loop has been found, the following additional steps will give us the starting node of the loop:</p>
<ol>
<li>Once a loop as been detected (step-3 above), move one of the pointers to the beginning (head) of the linked list. The second pointer remains where it was at the end of step-3.</li>
<li>Increment both pointers one node at a time. The node at which the two pointers meet will be the starting node of the loop!</li>
</ol>
<p>This algorithm isn’t too difficult compared to the algorithm for detecting a loop. However, the mental model seems a bit trickier. Why and how does it always find the start of the loop?</p>
<p><strong><br />
</strong></p>
<h3>How does the Algorithm work? An intuitive explanation:</h3>
<p>Here’s some explanation which would hopefully help you intuitively understand why the algorithm works, without going into a lot of mathematical detail.</p>
<p><strong>First, meeting point of two pointers in a loop</strong></p>
<p>Consider two pointers: a slow pointer S that increments by one node at each step, and a fast pointer F that increments by two nodes at each step (i.e. it is twice as fast as S). Both pointers start at the same time from the beginning of an n-node loop. In the time S covers n nodes. F will have covered 2n nodes and they will both meet at the start of the loop.</p>
<p>Now, let us say that the slow pointer S starts at the beginning of the loop, and the fast pointer F starts at node k (where k &lt; n) of the loop. As these two pointers move along the loop, they will meet at node (n-x).</p>
<p>What we really need to do is figure out x, as it will give us the node at which the two pointers meet inside the loop.</p>
<ol>
<li>When S takes n/2 steps, it will be at node n/2. During the same time, F will have taken 2(n/2) = n steps, and it will be at node (k+n). Since the we are inside a loop, F will be effectively back at node k.</li>
<li>In order for the two pointers to meet at node (n-x), S needs to take a further (n-x-n/2)=(n/2-x) steps and it will end up at node n-x. During the same time, F will have taken 2*(n/2-x)=(n-2x) steps and will be at node k+(n-2x). Given our assumption that both S and F meet at the same node:</li>
</ol>
<pre>		n-x = k+n-2x
	=&gt;	  x = k</pre>
<p>This means that if S starts from the start of the loop, and F starts k nodes into the loop, both of them will meet at node (n-k), i.e k nodes from the end of the loop. This is a key insight.</p>
<p><strong>Circular Linked List</strong></p>
<p>Now, coming back to the linked list that contains a loop. Suppose the start of the loop is m (e.g. m=3) nodes from the start of the linked list. Both S and F start at the beginning of the linked list [Figure-1].</p>
<div class="image">
<p><img style="display:block;margin-left:0;margin-right:auto;" title="Figure-1.jpg" src="http://umairsd.files.wordpress.com/2011/06/figure-1.jpg?w=500&#038;h=338" alt="Figure-1: Circular linked list with S and F pointers at the start" width="500" height="338" border="0" /></p>
<div><small>Figure-1: Circular linked list with S and F pointers at the start</small></div>
</div>
<p>&nbsp;</p>
<p>By the time S gets to node m (i.e. start of loop), F will be at node 2m [Figure-2]. This means that S will be at the start of the loop and F will be m nodes <strong>*into the loop*</strong>.</p>
<div class="image">
<p><img style="display:block;margin-left:0;margin-right:auto;" title="Figure-2.jpg" src="http://umairsd.files.wordpress.com/2011/06/figure-2.jpg?w=500&#038;h=345" alt="Figure-2: Circular linked list, with S at the start of loop and F m nodes into the loop" width="500" height="345" border="0" /></p>
<div><small>Figure-2: Circular linked list, with S at the start of loop and F m nodes into the loop</small></div>
</div>
<p>&nbsp;</p>
<p>Based on the discussion above, we already know that if S begins from the start of the loop and F starts from node m, they will meet m nodes from the end of the loop (i.e. the orange-node in [Figure-3]).</p>
<div class="image">
<p><img style="display:block;margin-left:0;margin-right:auto;" title="Figure-3.jpg" src="http://umairsd.files.wordpress.com/2011/06/figure-3.jpg?w=500&#038;h=317" alt="Figure-3: Both F and S meet m nodes from the end of the loop" width="500" height="317" border="0" /></p>
<div><small>Figure-3: Both F and S meet m nodes from the end of the loop</small></div>
</div>
<p>&nbsp;</p>
<p>At this point, keep the pointer F at the orange-node where the two pointers met (i.e. m-nodes from the start of the loop), and move the pointer S to the beginning of the linked list [Figure-4]. Now, if we increment both S and F *one node at a time*, it is obvious that they will meet at &#8216;Node-m&#8217; (red-node) of the list, which is the start of the loop.</p>
<div class="image">
<p><img style="display:block;margin-left:0;margin-right:auto;" title="Figure-4.jpg" src="http://umairsd.files.wordpress.com/2011/06/figure-4.jpg?w=500&#038;h=325" alt="Figure-4: S at the start of linked list, F at the point they met. Both increment one at a time from here-on" width="500" height="325" border="0" /></p>
<div><small>Figure-4: S at the start of linked list, F at the point they met. Both increment one at a time from here-on</small></div>
</div>
<p>&nbsp;</p>
<p>For the curious, here’s the Java code snippets for detecting a loop in a linked list and finding the starting node. The complete source code for my linked list project is at my Github page (<a href="https://github.com/umairsd/LinkedList-Java">https://github.com/umairsd/LinkedList-Java</a>):</p>
<p><pre class="brush: java;">
	/**
	 * Checks if the given linked list is a circular linked list (i.e. it
	 * contains a loop). This means a list in which a node's next pointer points
	 * to an earlier node, so as to make a loop in the linked list. For
	 * instance:
	 * 			A -&gt; B -&gt; C -&gt; D -&gt; E -&gt; C
	 *
	 * @param linkedList
	 *            the linked list to be tested
	 * @return true if there is a loop, false if there isn't
	 */
	public static boolean hasLoop(LinkedList linkedList) {
		if (linkedList == null || linkedList.getHead() == null) {
			return false;
		}

		IntegerNode slow = linkedList.getHead();
		IntegerNode fast = linkedList.getHead();

		while (true) {
			slow = slow.getNext();

			if (fast.getNext() != null) {
				fast = fast.getNext().getNext();
			} else {
				return false;
			}

			if (slow == null || fast == null) {
				return false;
			}

			if (slow == fast) {
				return true;
			}
		}
	}
</pre></p>
<p>&nbsp;</p>
<p><pre class="brush: java;">

	/**
	 * Returns the node at the start of a loop in the given circular linked
	 * list. A circular list is one in which a node's next pointer points
	 * to an earlier node, so as to make a loop in the linked list. For
	 * instance:
	 *
	 * input: A -&gt; B -&gt; C -&gt; D -&gt; E -&gt; C [the same C as earlier]
	 * output: C
	 *
	 * (CCI_0205)
	 *
	 * @param linkedList
	 *            list to be tested
	 * @return the node at the start of the loop if there is a loop, null
	 * otherwise
	 */
	public static IntegerNode findLoopStart(LinkedList linkedList) {
		if (linkedList == null || linkedList.getHead() == null) {
			return null;
		}

		IntegerNode loopStartNode = null;
		IntegerNode slow = linkedList.getHead();
		IntegerNode fast = linkedList.getHead();

		while (slow != null &amp;&amp; fast != null) {
			slow = slow.getNext();
			if (fast.getNext() == null) {
				loopStartNode = null;
				break;
			}
			fast = fast.getNext().getNext();

			// If slow and fast point to the same node, it means that the
			// linkedList contains a loop.
			if (slow == fast) {

				slow = linkedList.getHead();

				while (slow != fast) {
					// Keep incrementing the two pointers until they both
					// meet again. When this happens, both the pointers will
					// point to the beginning of the loop
					slow = slow.getNext(); // Can't be null, as we have a loop
					fast = fast.getNext(); // Can't be null, as we have a loop
				}

				loopStartNode = slow;
				break;
			}
		}

		return loopStartNode;
	}

</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/umairsd.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/umairsd.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/umairsd.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/umairsd.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/umairsd.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/umairsd.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/umairsd.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/umairsd.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/umairsd.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/umairsd.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/umairsd.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/umairsd.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/umairsd.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/umairsd.wordpress.com/186/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&amp;blog=9333327&amp;post=186&amp;subd=umairsd&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://umairsaeed.com/2011/06/23/finding-the-start-of-a-loop-in-a-circular-linked-list/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3d8419a4ace3305d6791158454f7f874?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">umairsd</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2011/06/figure-1.jpg" medium="image">
			<media:title type="html">Figure-1.jpg</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2011/06/figure-2.jpg" medium="image">
			<media:title type="html">Figure-2.jpg</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2011/06/figure-3.jpg" medium="image">
			<media:title type="html">Figure-3.jpg</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2011/06/figure-4.jpg" medium="image">
			<media:title type="html">Figure-4.jpg</media:title>
		</media:content>
	</item>
		<item>
		<title>Stern-Brocot Tree</title>
		<link>http://umairsaeed.com/2011/01/27/stern-brocot-tree/</link>
		<comments>http://umairsaeed.com/2011/01/27/stern-brocot-tree/#comments</comments>
		<pubDate>Thu, 27 Jan 2011 13:56:15 +0000</pubDate>
		<dc:creator>Umair</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Algos]]></category>
		<category><![CDATA[Arithmetic]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">https://umairsd.wordpress.com/?p=151</guid>
		<description><![CDATA[Stern-Brocot tree is a tree data structure whose vertices correspond to the set of non-negative rational numbers. Thus, this tree provides a very elegant way for constructing the set of fractions m/n, where m and n are relatively prime. To &#8230; <a href="http://umairsaeed.com/2011/01/27/stern-brocot-tree/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&amp;blog=9333327&amp;post=151&amp;subd=umairsd&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Stern-Brocot tree is a tree data structure whose vertices correspond to the set of non-negative rational numbers. Thus, this tree provides a very elegant way for constructing the set of fractions m/n, where m and n are relatively prime. To construct the tree, the basic idea is to start with two fractions (0/1, 1/0) and then repeat the following operation:</p>
<p><em>Insert (m+m&#8217;)/(n+n&#8217;) between two adjacent fractions m/n and m&#8217;/n&#8217;</em></p>
<p>The first step gives us the entry 1/1 between 0/1 and 1/0. Similarly, the 2nd step gives us two more: 0/1,1/2,1/1,2/1,1/0</p>
<p>Continuing on like this results in an infinite binary search tree which preserves the usual ordering of rational numbers.</p>
<p>The figure below shows the 1st 4 levels of the Stern-Brocot tree.</p>
<p><img title="Stern-Brocot.png" src="http://umairsd.files.wordpress.com/2011/01/stern-brocot.png?w=500&#038;h=340" border="0" alt="Stern-Brocot.png" width="500" height="340" /></p>
<h3>Finding the Path to k in Stern-Brocot Tree</h3>
<p>The path from the root of the tree to a number k in the Stern-Brocot tree can be found using binary search. At each node, k will either be in the left half of the tree, or the right half. We continue down the left or right subtree until we finally find k.</p>
<ul>
<li>Initialize the left fraction L to 0/1 and right fraction R to 1/0</li>
<li>Repeat the following until k is found:
<ul>
<li>Compute the mediant M (which is (m+m&#8217;)/(n+n&#8217;) )</li>
<li>If (k&gt;M), then k is in the right half of the tree. L:=M and continue.</li>
<li>Else If (M&gt;k), then k is in the left half of the tree. R:=M and continue.</li>
<li>Else q=M, terminate search.</li>
</ul>
</li>
</ul>
<p><strong>Implementation</strong></p>
<p>There&#8217;s a couple of things to tackle in our implementation. First, I need an easy way to represent fractions, so I create my own <em>SternBrocotFraction</em> class. I deliberately chose to make it very specific to this algorithm because I needed a special way to handle the fraction 1/0 (which by definition is greater than all other rationals).</p>
<p>Secondly, I needed a good way to represent the path from the root of the tree to k. I do this by using a <em>StringBuilder</em>, and at each step I append either the letter &#8216;L&#8217; or &#8216;R&#8217; depending on which sub-tree we take. When the search is finished, this gives us a <em>String</em> representation of the path from the root of the tree to the number k. This approach is similar to the approach advocated by ACM Programming Competitions for <a href="http://acm.uva.es/p/v100/10077.html">the &#8220;Stern-Brocot Number System&#8221; problem</a>.</p>
<p>Here&#8217;s the code to find path to a number k:</p>
<p><pre class="brush: java;">
package com.umairsaeed.algorithm;

public class SternBrocotPath {
	private static final char LEFT_SUB = 'L';
	private static final char RIGHT_SUB = 'R';

	public String findPathTo(SternBrocotFraction f) {
		SternBrocotFraction L = new SternBrocotFraction(0, 1);
		SternBrocotFraction R = new SternBrocotFraction(1, 0);

		StringBuilder results = new StringBuilder();
		SternBrocotPath.find(f, L, R, results);
		return results.toString();
	}

	public static void find(SternBrocotFraction f,
			SternBrocotFraction L,
			SternBrocotFraction R,
			StringBuilder results)
	{
		SternBrocotFraction M = L.add(R);

		if (M.compareTo(f) &lt; 0) {
			L = M;
			results.append(RIGHT_SUB);
			SternBrocotPath.find(f, L, R, results);
		} else if (M.compareTo(f) &gt; 0) {
			R = M;
			results.append(LEFT_SUB);
			SternBrocotPath.find(f, L, R, results);
		}
		return;
	}
}
</pre></p>
<p>The special SternBrocotFraction class is:</p>
<p><pre class="brush: java;">
package com.umairsaeed.algorithm;

public class SternBrocotFraction implements
				Comparable&lt;SternBrocotFraction&gt; {
	private int numerator;
	private int denominator;

	public SternBrocotFraction(int numerator, int denominator) {
		if (denominator &lt; 0) {
			numerator *= -1;
			denominator *= -1;
		}

		this.numerator = numerator;
		this.denominator = denominator;
	}

	public double doubleValue() {
		if (this.denominator == 0) {
			return Double.MAX_VALUE;
		} else {
			return (double) this.numerator /
						(double) this.denominator;
		}
	}

	public SternBrocotFraction add(SternBrocotFraction other) {
		return new SternBrocotFraction(
				this.numerator + other.numerator,
				this.denominator + other.denominator);
	}

	public int compareTo(SternBrocotFraction other) {
		if (this.doubleValue() &lt; other.doubleValue()) {
			return -1;
		} else if (this.doubleValue() &gt; other.doubleValue()) {
			return 1;
		}
		return 0;
	}
}
</pre></p>
<p>Finally, some test code to exercise my class:</p>
<p><pre class="brush: java;">
package com.umairsaeed.algorithm;

public class SternBrocotTester {
	public static void main(String[] args) {
		testSternBrocotPath();
	}

	public static void testSternBrocotPath() {
		SternBrocotPath t = new SternBrocotPath();

		SternBrocotFraction f = new SternBrocotFraction(5, 7);
		System.out.println(t.findPathTo(f));

		f = new SternBrocotFraction(19, 101);
		System.out.println(t.findPathTo(f));

		f = new SternBrocotFraction(977, 331);
		System.out.println(t.findPathTo(f));

		f = new SternBrocotFraction(1049, 7901);
		System.out.println(t.findPathTo(f));
	}
}
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/umairsd.wordpress.com/151/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/umairsd.wordpress.com/151/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/umairsd.wordpress.com/151/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/umairsd.wordpress.com/151/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/umairsd.wordpress.com/151/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/umairsd.wordpress.com/151/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/umairsd.wordpress.com/151/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/umairsd.wordpress.com/151/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/umairsd.wordpress.com/151/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/umairsd.wordpress.com/151/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/umairsd.wordpress.com/151/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/umairsd.wordpress.com/151/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/umairsd.wordpress.com/151/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/umairsd.wordpress.com/151/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&amp;blog=9333327&amp;post=151&amp;subd=umairsd&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://umairsaeed.com/2011/01/27/stern-brocot-tree/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3d8419a4ace3305d6791158454f7f874?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">umairsd</media:title>
		</media:content>

		<media:content url="http://umairsd.files.wordpress.com/2011/01/stern-brocot.png" medium="image">
			<media:title type="html">Stern-Brocot.png</media:title>
		</media:content>
	</item>
		<item>
		<title>Java Enum Puzzler</title>
		<link>http://umairsaeed.com/2009/09/29/java-enum-puzzler/</link>
		<comments>http://umairsaeed.com/2009/09/29/java-enum-puzzler/#comments</comments>
		<pubDate>Tue, 29 Sep 2009 22:31:33 +0000</pubDate>
		<dc:creator>Umair</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[enum]]></category>
		<category><![CDATA[puzzle]]></category>

		<guid isPermaLink="false">http://umairsd.wordpress.com/2009/09/29/java-enum-puzzler/</guid>
		<description><![CDATA[Recently, I ran into an interesting bit of code related to Java enumerations. Here’s a contrived minimal sample: When this code is run, an intuitive expectation is to see the following printed to the console: BRAVO CHARLIE ALPHA However, when &#8230; <a href="http://umairsaeed.com/2009/09/29/java-enum-puzzler/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&amp;blog=9333327&amp;post=27&amp;subd=umairsd&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Recently, I ran into an interesting bit of code related to Java enumerations. Here’s a contrived minimal sample:</p>
<pre><pre class="brush: java;">
/*
 * Some arbitrary resource type
 */
interface Resource {
	public Resource getResource();
}

enum A implements Resource{
	ALPHA (B.BRAVO);
	
	private Resource res;
	private A (Resource res){ this.res = res; }
	public Resource getResource(){ return res; }
}

enum B implements Resource{
	BRAVO (C.CHARLIE);

	private Resource res;
	private B (Resource res){ this.res = res; }
	public Resource getResource(){ return res; }

}

enum C implements Resource{
	CHARLIE (A.ALPHA);

	private Resource res;
	private C (Resource res){ this.res = res; }
	public Resource getResource(){ return res; }
}


class EnumTester{
	public static void main(String [] args){
		System.out.println(A.ALPHA.getResource());	
		System.out.println(B.BRAVO.getResource());	
		System.out.println(C.CHARLIE.getResource());
	}
}
</pre></pre>
<p>When this code is run, an intuitive expectation is to see the following printed to the console:</p>
<blockquote>
<table border="0" cellspacing="0" cellpadding="2" width="37">
<tbody>
<tr>
<td valign="top" width="35"><font face="Courier New">BRAVO</font></td>
</tr>
<tr>
<td valign="top" width="35"><font face="Courier New">CHARLIE</font></td>
</tr>
<tr>
<td valign="top" width="35"><font face="Courier New">ALPHA</font></td>
</tr>
</tbody>
</table>
</blockquote>
<p>However, when I actually run the code we see:</p>
<blockquote>
<table border="0" cellspacing="0" cellpadding="2" width="37">
<tbody>
<tr>
<td valign="top" width="35"><font face="Courier New">BRAVO</font></td>
</tr>
<tr>
<td valign="top" width="35"><font face="Courier New">CHARLIE</font></td>
</tr>
<tr>
<td valign="top" width="35"><font face="Courier New">null</font></td>
</tr>
</tbody>
</table>
</blockquote>
<p>While this may seem a bit funky, the key is to understand what enum constants mean in Java. The key question to address is: “when is the constructor for an enumerated type invoked”. To answer this, it is helpful to remember that enum constants are implicitly <font face="Courier New"><font size="2">public static final</font>.</font> Java guarantees that:</p>
<ul>
<li>Static variables in a class are initialized before any object of that class can be created </li>
<li>Static variables in a class are initialized before any static method of the class runs </li>
</ul>
<p>Knowing this, the behavior of the above code snippet becomes clearer. Here’s what happens in the main method:</p>
<ol>
<li>The fun happens at line 35, when we print&#160;&#160; <font face="Courier New">A.<em>ALPHA</em>.getResource()</font>. Behind the scene, the class loader loads enumeration A into memory (i.e. initializes A). </li>
<li>Once A is loaded into memory, the enum constant <em><font face="Courier New">ALPHA</font></em> gets created via call to the constructor where <font face="Courier New">B.<em>BRAVO</em></font> is passed in as the argument. </li>
<li>At this point, enumeration B is initialized and enum constant <em><font face="Courier New">BRAVO</font></em> gets created via a call to the constructor where <font face="Courier New">C.<em>CHARLIE</em></font> is passed in as the argument. </li>
<li>Same as before, now enumeration C is initialized (i.e. loaded into memory). Now here’s where things become interesting. </li>
<li>Immediately after the initialization of C, we create the enum constant <em><font face="Courier New">CHARLIE</font></em> via a call to the constructor and pass in <font face="Courier New">A.<em>ALPHA</em></font> as the argument. However, <font face="Courier New">A.<em>ALPHA</em></font> has not been instantiated yet, and therefore enum constant <em><font face="Courier New">CHARLIE</font></em> gets null as the value of its resource instance variable.&#160; </li>
</ol>
<p>This means that once the statement <font face="Courier New">A.<em>ALPHA</em>.getResource()</font> is evaluated, A, B and C are all loaded into memory and all the corresponding enum constants have already been instantiated. Lines 35-37 simply then print the corresponding resources for each enum constant. </p>
</p>
<p><strong></strong></p>
</p>
<p><strong><font size="4">A Possible Solution</font></strong></p>
<p>It is obvious that the entire problem stems from the cyclic dependency between A, B and C. Usually (but <a href="http://beust.com/weblog/archives/000208.html" target="_blank">not always</a>), this is an indication of a bad design choice and the fix is to simply get rid of the cyclic dependency. Assuming we want to keep the dependency, what are our options then?</p>
<p>Our solutions lies in Java&#8217;s ability to allow <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html" target="_blank">instance-specific methods on enumerations</a>. This is shown in the code below.</p>
<p>Running the following code with the EnumTester main method above will give us the results we wanted, without the problems caused by the previous approach.</p>
<pre><pre class="brush: java;">
enum A implements Resource{
	ALPHA { public Resource getResource() {return B.BRAVO; } };
	
	public abstract Resource getResource();
}

enum B implements Resource{
	BRAVO { public Resource getResource() { return C.CHARLIE; } };
	
	public abstract Resource getResource();
}

enum C implements Resource{
	CHARLIE { public Resource getResource() { return A.ALPHA; }};
	
	public abstract Resource getResource();
}
</pre></pre>
<p>What do you think? Do you know of any other ways to resolve the cyclic dependency? Have you seen any other weirdness related to Java’s Enums? </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/umairsd.wordpress.com/27/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&amp;blog=9333327&amp;post=27&amp;subd=umairsd&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://umairsaeed.com/2009/09/29/java-enum-puzzler/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3d8419a4ace3305d6791158454f7f874?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">umairsd</media:title>
		</media:content>
	</item>
	</channel>
</rss>
