<?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/"
	>

<channel>
	<title>Deep in Code</title>
	<atom:link href="http://blog.deepincode.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.deepincode.com</link>
	<description>Take a deep dive into code</description>
	<lastBuildDate>Sun, 18 Jul 2010 03:47:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.2</generator>
		<item>
		<title>Amazon SimpleDB Developer Guide by PACKT</title>
		<link>http://blog.deepincode.com/2010/07/amazon-simpledb-developers-guide-by-packt/</link>
		<comments>http://blog.deepincode.com/2010/07/amazon-simpledb-developers-guide-by-packt/#comments</comments>
		<pubDate>Sun, 18 Jul 2010 03:47:34 +0000</pubDate>
		<dc:creator>Deepak Anupalli</dc:creator>
				<category><![CDATA[Cloud]]></category>

		<guid isPermaLink="false">http://deepjava.wordpress.com/?p=32</guid>
		<description><![CDATA[I have reviewed the book, Amazon SimpleDB Developer Guide by PACKT publisher, which got released last month. Amazon SimpleDB is a schema-less, highly scalable datastore which provides eventual consistency. This book introduces developer&#8217;s to SimpleDB API &#38; libraries in different languages, Java, PHP &#38; Python. It discusses the differences between relational databases and SimpleDB, and ]]></description>
			<content:encoded><![CDATA[<p>I have reviewed the book, <a title="Amazon SimpleDB Developer's Guide" href="https://www.packtpub.com/amazon-simpledb-database-developer-guide/book">Amazon SimpleDB Developer Guide by PACKT</a> publisher, which got released last month. Amazon SimpleDB is a schema-less, highly scalable datastore which provides eventual consistency.</p>
<p><a title="Amazon SimpleDB Developer's Guide" href="http://www.amazon.com/Amazon-SimpleDB-Developer-Prabhakar-Chaganti/dp/1847197345"><img src="http://ecx.images-amazon.com/images/I/510R3ZdMkjL._SL500_AA300_.jpg" alt="Amazon SimpleDB Developer Guide" /></a></p>
<p>This book introduces developer&#8217;s to SimpleDB API &amp; libraries in different languages, Java, PHP &amp; Python. It discusses the differences between relational databases and SimpleDB, and how to deal with the No SQL, No Schema paradigm. It also dwells into profiling requests based on the execution times and box usage statistics, and adding cache layers using memcached.</p>
<script type="text/javascript" src="http://cdn.socialtwist.com/2011021149263/script.js"></script><a class="st-taf" href="http://tellafriend.socialtwist.com:80" onclick="return false;" style="border:0;padding:0;margin:0;"><img alt="SocialTwist Tell-a-Friend" style="border:0;padding:0;margin:0;" src="http://images.socialtwist.com/2011021149263/button.png" onmouseout="STTAFFUNC.hideHoverMap(this)" onmouseover="STTAFFUNC.showHoverMap(this, '2011021149263', 'http%3A%2F%2Fblog.deepincode.com%2F2010%2F07%2Famazon-simpledb-developers-guide-by-packt%2F', 'Amazon+SimpleDB+Developer+Guide+by+PACKT')" onclick="STTAFFUNC.cw(this, {id:'2011021149263', link: 'http%3A%2F%2Fblog.deepincode.com%2F2010%2F07%2Famazon-simpledb-developers-guide-by-packt%2F', title: 'Amazon+SimpleDB+Developer+Guide+by+PACKT' });"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.deepincode.com/2010/07/amazon-simpledb-developers-guide-by-packt/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Playing around with exception stack traces</title>
		<link>http://blog.deepincode.com/2007/08/playing-around-with-exception-stack-traces/</link>
		<comments>http://blog.deepincode.com/2007/08/playing-around-with-exception-stack-traces/#comments</comments>
		<pubDate>Wed, 01 Aug 2007 18:51:11 +0000</pubDate>
		<dc:creator>Deepak Anupalli</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://deepjava.wordpress.com/2007/08/01/playing-around-with-exception-stack-traces/</guid>
		<description><![CDATA[Debugging exception stack traces is inevitable for any Java developer. When there is a failure at the customer end, our first reaction would be &#8220;Are there any exception stack traces?&#8221;. Stack traces play a key role for Java software to provide essential feedback on failures to the end user as well as the developer. During ]]></description>
			<content:encoded><![CDATA[<p>Debugging exception stack traces is inevitable for any Java developer. When there is a failure at the customer end, our first reaction would be &#8220;Are there any exception stack traces?&#8221;. Stack traces play a key role for Java software to provide essential feedback on failures to the end user as well as the developer.</p>
<p>During the development process, there would be a lot of focus on exception handling mechanisms. The intention is to deduce or arrive at the cause for any failure with minimal effort. Nevertheless, there could be situations where you end up debugging or not able to debug bad stack traces which hardly give any information about the cause of the failure. In this post, I would like to focus on these situations and discuss possible solutions to fix such bad stack traces.</p>
<p>Dynamic proxy invocation is a well established pattern in Java. Especially, Containers that provide middle-ware services use this pattern extensively to intercept the calls and embed their services.</p>
<p><span style="font-size:1.2em;">Stack traces while invoking Dynamic Proxies</span></p>
<p>Let us take a look at the invocation of dynamic Proxy instances and the stack traces of exceptions thrown during invocation.</p>
<pre><span class="Modifier">public</span> <span class="Type">interface</span> Customer {
    <span class="Modifier">public</span> <span class="Type">void</span> login() throws LoginException;
}

<span class="Modifier">public</span> <span class="Type">interface</span> Administrator {
    <span class="Modifier">public</span> <span class="Type">void</span> login() throws LoginException;
}

<span class="Modifier">public</span> <span class="Type">class</span> LoginProvider implements InvocationHandler {

    <span class="Modifier">public</span> <span class="Type">Object</span> invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        ...
        <span class="Statement">throw</span> <span class="Keyword">new</span> LoginException(<span class="String">"Login failed !!"</span>);
        ...
    }

    <span class="Modifier">public</span> <span class="Modifier">static</span> <span class="Type">void</span> main(String[] args) throws Exception {
        Customer cust = (Customer)Proxy.newProxyInstance(
                ClassLoader.getSystemClassLoader(),
                <span class="Keyword">new</span> Class[]{Customer.<span class="Keyword">class</span>},
                <span class="Keyword">new</span> LoginProvider());
        cust.login();

        Administrator admin = (Administrator)Proxy.newProxyInstance(
                ClassLoader.getSystemClassLoader(),
                <span class="Keyword">new</span> Class[]{Administrator.<span class="Keyword">class</span>},
                <span class="Keyword">new</span> LoginProvider());
        admin.login();
    }
}</pre>
<p>In the above example, dynamic proxy instances are created for Customer and Administrator interfaces, and implementation for login() method is provided by the LoginProvider invocation handler. LoginProvider throws a LoginException when there is any failure during login, as shown below.</p>
<pre>Exception in thread "main" proxies.LoginException: Login failed !!
    at proxies.LoginProvider.invoke(LoginProvider.java:18)
    at proxies.$Proxy1.login(Unknown Source)
    at proxies.LoginProvider.main(LoginProvider.java:32)</pre>
<p>When you look at the above stack trace, first thing that comes into mind is &#8220;why did login fail?&#8221; and &#8220;who is trying to login?&#8221;. You can figure out why login has failed by looking at the exception message or the cause, but you can never get to know whose login has failed. In the above stack trace, you can see that the &#8220;$Proxy&#8221; masks information about Customer or Administrator interfaces, giving no clue on whose login has failed. Unless we have the source for LoginProvider we can&#8217;t deduce the problem, as we need to figure out the whereabouts of proxy&#8217;s creation and the interfaces it implements. Now, this becomes even harder if the interfaces implemented by the Proxy are read from configuration (Xml/Annotation etc.).</p>
<p><span style="font-size:1.2em;">Tweaking exception stack traces</span></p>
<p>Many a times though there is enough flexibility in the programming language, we would hardly find a way to make use of it. One such a thing is modifying stack trace of an exception and we can explore this feature to fix our bad stack trace.</p>
<p>It is very simple to modify the stack trace, java.lang.Throwable provides getStackTrace() and setStackTrace() methods to get or set an array of StackTraceElements. So, you can create your own array of these StackTraceElements and set the array back on the Throwable instance. Each StackTraceElement can be instantiated and contain a customized class name, file name, line number etc.</p>
<pre><span class="Modifier">public</span> <span class="Type">void</span> setStackTrace(StackTraceElements[] stackTrace) { … }</pre>
<p>Understanding the above exception stack trace is really difficult for end users, system administrators or developers. Instead, if we can replace &#8220;$Proxy&#8221; with useful information like interface name, deployment name or JNDI name then we can quickly relate the problem to the component that has failed.</p>
<pre>Exception in thread "main" proxies.LoginException: Login failed !!
    at proxies.LoginProvider.invoke(LoginProvider.java:18)
    at proxies.Customer.login(Unknown Source)
    at proxies.LoginProvider.main(LoginProvider.java:32)</pre>
<p>In the above stack trace proxy&#8217;s occurrence has been replaced with the interface name it implements. Now, you clearly know whose login has failed by looking at the stack trace. Someone can immediately point out that instead of tweaking the stack trace it would have been better to improve exception messaging and if required wrap the exception to contain relevant information. Yes, actually there is a trade-off between wrapping the cause and tweaking the exception stack trace. The trade-off with the tweaking approach is you can put up a generic stack trace manipulator without much knowledge about the exception. Where as in the other case we need to understand each type of exception and do the necessary wrapping.</p>
<p><span style="font-size:1.2em;">Debuggers and Stack traces</span></p>
<p><strong>Exceptions from a JSP page</strong></p>
<p>How do you debug exceptions thrown when you access a JSP page? Aaahh..! Its a terrible pain to look into the generated servlet java files and relate the failure to the JSP line number. Some of the JSP containers support <a href="http://jcp.org/en/jsr/detail?id=45">JSR-45</a>, Java Debugging Support for Other Languages, to map the generated servlet java line numbers to the JSP line numbers and vice versa (through SMAP). This information is embedded into the servlet class file and is useful to debugger tools to track the line numbers of the JSP page back, when the servlet gets executed behind.</p>
<p>SMAP information is actually available to the JVM, but unfortunately VM doesn&#8217;t generate the stack trace based on this information. There is a <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4972961">bug</a> reported for this issue and you can vote for this. Hence, JSP Containers need some way of transforming the exception stack traces to contain JSP line numbers, making it more readable to an end user. One of the ways could be the above suggested method to use setStackTrace() to post-process the exception stack trace after it has been raised.</p>
<p><strong>Exceptions from obfuscated code</strong></p>
<p>Another similar use case where we need a readable stack trace is, when the code is Obfuscated. If the obfuscation tools support JSR-45 and provide the obfuscated code to the original code line number mapping through SMAP, then we would have cleaner stack traces along with debugging support for obfuscated code.</p>
<p class="zoundry_bw_tags"><!-- Tag links generated by Zoundry Blog Writer. Do not manually edit. http://www.zoundry.com --><br />
<span class="ztags"><span class="ztagspace">Technorati</span> : <a class="ztag" rel="tag" href="http://technorati.com/tag/java">java</a></span></p>
<script type="text/javascript" src="http://cdn.socialtwist.com/2011021149263/script.js"></script><a class="st-taf" href="http://tellafriend.socialtwist.com:80" onclick="return false;" style="border:0;padding:0;margin:0;"><img alt="SocialTwist Tell-a-Friend" style="border:0;padding:0;margin:0;" src="http://images.socialtwist.com/2011021149263/button.png" onmouseout="STTAFFUNC.hideHoverMap(this)" onmouseover="STTAFFUNC.showHoverMap(this, '2011021149263', 'http%3A%2F%2Fblog.deepincode.com%2F2007%2F08%2Fplaying-around-with-exception-stack-traces%2F', 'Playing+around+with+exception+stack+traces')" onclick="STTAFFUNC.cw(this, {id:'2011021149263', link: 'http%3A%2F%2Fblog.deepincode.com%2F2007%2F08%2Fplaying-around-with-exception-stack-traces%2F', title: 'Playing+around+with+exception+stack+traces' });"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.deepincode.com/2007/08/playing-around-with-exception-stack-traces/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Improper use of Generics could breach type safety</title>
		<link>http://blog.deepincode.com/2007/03/improper-use-of-generics-could-breach-type-safety/</link>
		<comments>http://blog.deepincode.com/2007/03/improper-use-of-generics-could-breach-type-safety/#comments</comments>
		<pubDate>Tue, 20 Mar 2007 02:31:51 +0000</pubDate>
		<dc:creator>Deepak Anupalli</dc:creator>
				<category><![CDATA[Java5]]></category>

		<guid isPermaLink="false">http://deepjava.wordpress.com/2007/03/20/improper-use-of-generics-could-breach-type-safety/</guid>
		<description><![CDATA[I was going through Java discussion forums and happened to come across an interesting discussion related to Generics. It was about a loop hole in the Java Generics feature that allows a method to throw a Checked Exception without declaring it in the throws clause. This is definitely going to be freaky and I wouldn&#8217;t ]]></description>
			<content:encoded><![CDATA[<p>I was going through Java discussion forums and happened to come across an interesting discussion related to Generics. It was about a loop hole in the Java Generics feature that allows a method to throw a Checked Exception without declaring it in the throws clause.</p>
<p>This is definitely going to be freaky and I wouldn&#8217;t encourage you to take advantage of this in your development. Initially I thought this could be a loop hole in the Compiler implementation, but later realized that the behavior is inherent with the Generics design.</p>
<pre>
<span class="Modifier">public</span> <span class="Type">class</span> RethrowCheckedException {
    <span class="Modifier">public</span> <span class="Modifier">static</span> <span class="Type">void</span> rethrow(Throwable t) {//No throws clause
        RethrowCheckedException.&lt;RuntimeException&gt;throwing(t);
    }

    <span class="Modifier">public</span> <span class="Modifier">static</span> &lt;T extends Throwable&gt; <span class="Type">void</span> throwing(Throwable t) throws T {
        <span class="Statement">throw</span> (T)t;
    }
    <span class="Modifier">public</span> <span class="Modifier">static</span> <span class="Type">void</span> main(String[] args) {
        <span class="Statement">try</span> {
            <span class="Statement">throw</span> <span class="Keyword">new</span> Exception("dummy");
        } <span class="Statement">catch</span> (Exception e) {
            rethrow(e);
        }
    }
}</pre>
<p>Using the <span style="font-style:italic;">rethrow()</span> method we can make java.lang.Exception to escape from <span style="font-style:italic;">main()</span> without declaring it in its throws clause. The type &lt;RuntimeException&gt; specified while invoking the <span style="font-style:italic;">throwing()</span> method is know as &#8220;explicit type argument&#8221;. (which is complementary to the type inference discussed below)</p>
<p><span style="font-size:1.2em;">Type Inference</span></p>
<p>To understand how the above thing works, we need to get an idea about type inference and explicit typing. Take a look at the the following example</p>
<pre>
<span class="Modifier">public</span> <span class="Type">class</span> ArrayStore {
    <span class="Modifier">public</span> <span class="Modifier">static</span> &lt;T&gt; <span class="Type">void</span> store(T[] array, T item) {
        <span class="Statement">if</span> (array.length &gt; 0)
            array[0] = item;
    }
    <span class="Modifier">public</span> <span class="Modifier">static</span> <span class="Type">void</span> main(String[] args) {
        store(<span class="Keyword">new</span> String[1], <span class="String">"abc"</span>); <span class="InlineComment">//ok</span>
        store(<span class="Keyword">new</span> String[1], <span class="Keyword">new</span> Integer(10)); <span class="InlineComment">//??</span>
    }
}</pre>
<p>Surprisingly, both the <span style="font-style:italic;">store</span> method invocations shown, compile. Compiler infers T to String for the first <span style="font-style:italic;">store()</span> invocation as both the arguments are Strings, this process is known as &#8220;type inference&#8221;. We expect the second one to fail as T cannot be evaluated to both a String as well as an Integer. But, the Compiler infers T to a common super class or interface other than java.lang.Object. As String and Integer have Serializable and Comparable as super interfaces, Compiler deduces T to be a Serializable or Comparable and allows compilation. The result of which is an ArrayStoreException at runtime, defying the whole point of Generics and type safety.</p>
<p>How do we resolve this problem? We can use the &#8220;explicit type argument&#8221; in such cases.</p>
<pre></pre>
<pre>ArrayStore.&lt;String&gt;store(<span class="Keyword">new</span> String[1], <span class="Keyword">new</span> Integer(10)); <span class="InlineComment">//compilation Error</span></pre>
<p>Explicitly specifying the type argument as String, forces the compiler to evaluate T to String (overriding the compiler&#8217;s type inference mechanism) and hence compilation fails.</p>
<p>Now that we got a hang on type inference, we&#8217;ll get back to the loop hole.</p>
<pre>
<span class="Modifier">public</span> <span class="Modifier">static</span> &lt;T extends Throwable&gt; <span class="Type">void</span> throwing(Throwable t) throws T {
    <span class="Statement">throw</span> (T)t;
}</pre>
<p>The <span style="font-style:italic;">throwing()</span> method defines type &lt;T extends Throwable&gt; which is declared in its throws clause and is no way related to the argument passed. The <span style="font-style:italic;">rethrow()</span> method explicitly specifies the type as RuntimeException, making the method signature of the <span style="font-style:italic;">throwing()</span> method to appear as shown below, at compile time.</p>
<pre>
<span class="Modifier">public</span> <span class="Modifier">static</span> <span class="Type">void</span> throwing(Throwable t) throws RuntimeException {
    <span class="Statement">throw</span> (RuntimeException)t;
}</pre>
<p>Compiler evaluates the method signature by replacing the type variable T with its inferred or explicitly specified type, which is RuntimeException in our case. As a result of this Compiler doesn&#8217;t enforce exception handling or re-throwing it in the <span style="font-style:italic;">rethrow()</span> method. After compilation and type erasure, all the generic type information is erased as shown below.</p>
<pre>
<span class="Modifier">public</span> <span class="Modifier">static</span> <span class="Type">void</span> throwing(Throwable t) throws Throwable {
    <span class="Statement">throw</span> (Throwable)t;
}</pre>
<p><span style="font-size:1.2em;">Some thoughts</span><br />
Type inference or explicit type argument could do some damage when the Generic type information is not captured properly. In the loop hole case, since the exception argument passed to the <span style="font-style:italic;">throwing()</span> method is not related to the Generic type (T), compiler was blind folded. If we modify the method signature as shown below, method invocation fails to compile.</p>
<pre>
<span class="Modifier">public</span> <span class="Modifier">static</span> &lt;T extends Throwable&gt; <span class="Type">void</span> throwing(T t) throws T {
    <span class="Statement">throw</span> (T)t;
}</pre>
<p>Similarly, in the ArrayStore example we cannot expect the programmer to invoke the store method by explicitly specifying the type everytime at the calling context. A better way of capturing the generic type information in this case is to establish a relationship between Type variables(T&#8217;s), to enforce expected compile time checks.</p>
<pre>
<span class="Modifier">public</span> <span class="Modifier">static</span> &lt;T, S extends T&gt; <span class="Type">void</span> store(T[] array, S item) { ... }</pre>
<p>And interestingly, the following generic type declarations work as expected unlike the ArrayStore example.</p>
<pre>
<span class="Modifier">public</span> <span class="Modifier">static</span> &lt;T&gt; setMap(Map&lt;T, T&gt; map) { ... }
<span class="Modifier">public</span> <span class="Modifier">static</span> &lt;T&gt; addToList(List&lt;T&gt; list, T element) { ...}</pre>
<pre>
addToList(<span class="Keyword">new</span> ArrayList&lt;String&gt;(), <span class="Keyword">new</span> Integer(10)); <span class="InlineComment">//fails to compile</span></pre>
<p>Java Language Specification(JLS) 3.0, 15.12.2.7 states &#8220;The process of type inference is inherently complex.&#8221;</p>
<p>Yes indeed it is really complex to understand type inference. All this appeals for better understanding of the type inference mechanism and how it applies. Probably you can get more information from <a href="http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#Type%20Argument%20Inference" title="FAQ by Angelika Langer">FAQ by Angelika Langer</a>.</p>
<p class="zoundry_bw_tags">   <!-- Tag links generated by Zoundry Blog Writer. Do not manually edit. http://www.zoundry.com --><br />
<span class="ztags"><span class="ztagspace">Technorati</span> : <a href="http://technorati.com/tag/deepjava" class="ztag" rel="tag">deepjava</a>, <a href="http://technorati.com/tag/java" class="ztag" rel="tag">java</a>, <a href="http://technorati.com/tag/java5" class="ztag" rel="tag">java5</a></span><br />
<span class="ztags"><span class="ztagspace">Del.icio.us</span> : <a href="http://del.icio.us/tag/java" class="ztag" rel="tag">java</a>, <a href="http://del.icio.us/tag/java5" class="ztag" rel="tag">java5</a></span></p>
<script type="text/javascript" src="http://cdn.socialtwist.com/2011021149263/script.js"></script><a class="st-taf" href="http://tellafriend.socialtwist.com:80" onclick="return false;" style="border:0;padding:0;margin:0;"><img alt="SocialTwist Tell-a-Friend" style="border:0;padding:0;margin:0;" src="http://images.socialtwist.com/2011021149263/button.png" onmouseout="STTAFFUNC.hideHoverMap(this)" onmouseover="STTAFFUNC.showHoverMap(this, '2011021149263', 'http%3A%2F%2Fblog.deepincode.com%2F2007%2F03%2Fimproper-use-of-generics-could-breach-type-safety%2F', 'Improper+use+of+Generics+could+breach+type+safety')" onclick="STTAFFUNC.cw(this, {id:'2011021149263', link: 'http%3A%2F%2Fblog.deepincode.com%2F2007%2F03%2Fimproper-use-of-generics-could-breach-type-safety%2F', title: 'Improper+use+of+Generics+could+breach+type+safety' });"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.deepincode.com/2007/03/improper-use-of-generics-could-breach-type-safety/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Understanding Generics with Collections</title>
		<link>http://blog.deepincode.com/2006/12/understanding-generics-with-collections-2/</link>
		<comments>http://blog.deepincode.com/2006/12/understanding-generics-with-collections-2/#comments</comments>
		<pubDate>Fri, 22 Dec 2006 06:09:06 +0000</pubDate>
		<dc:creator>Deepak Anupalli</dc:creator>
				<category><![CDATA[Java5]]></category>

		<guid isPermaLink="false">http://deepjava.wordpress.com/2006/12/22/understanding-generics-with-collections-2/</guid>
		<description><![CDATA[In Java (prior to 5.0), a lot of times you are compelled to downcast your object to a more specific one. For example, when you add a String to a List, and when you want to retrieve your String back then you need to downcast. List myList = new ArrayList(); myList.add("abc"); String str = (String)myList.get(0); ]]></description>
			<content:encoded><![CDATA[<p>In Java (prior to 5.0), a lot of times you are compelled to downcast your object to a more specific one. For example, when you add a String to a List, and when you want to retrieve your String back then you need to downcast.</p>
<pre><span style="font-family:'Courier New';">List myList = <span class="Keyword">new</span> ArrayList();
myList.add(<span class="String">"abc"</span>);
String str = (String)myList.get(0);

</span></pre>
<p>Downcast is inevitable. Moreover, adding objects of any type to the list is allowed and the developer is responsible to remember the type of each object and perform the appropriate downcast while retrieving them. This gives a way to the type safety problems in Java, as every downcast in the code is a potential case for the wicked ClassCastException. Generics have been introduced to rescue us from these situations, they let you mark the collection to contain elements of a particular data type only, say a List of Strings. The syntax to specify a List of Strings would look like this. (Note: &#8216;type&#8217; refers to any class definition in Java, e.g. String, Integer, Collection, MyClass etc. are all denoted as types.)</p>
<pre><span style="font-family:'Courier New',courier,monospace;">List&lt;String&gt; myList = <span class="Keyword">new</span> ArrayList&lt;String&gt;();
myList.add(<span class="String">"abc"</span>);
String str = myList.get(0);
</span></pre>
<p>The syntax is fairly simple, you need to specify the &#8216;type&#8217; of the Collection in the angular brackets following the Collection type. Such types are known as Generic types or Parameterized types. We&#8217;ll get to know more about defining collection types and substitution in the following sections.</p>
<p>With the above syntax, it is not allowed to add objects or retrieve objects of any other type other than String to the above List and doing that would result in a compile-time error. This is much better than the ClassCastException at runtime, and would definitely save a lot of your development time, isn&#8217;t it? And more importantly the downcast should be made extinct now, as the type of the elements within the collection is explicity informed to the compiler through the Generic syntax.</p>
<p><span style="font-size:1.2em;">Purpose of Generics</span><br />
Generics make your program well formed enabling the compiler to perform enough type checks based on the static type information provided and avoids unexpected type errors that could occur at runtime. Let us get into more practical matters.</p>
<p><span style="font-size:1.2em;">Collections and Substitution rules</span><br />
Collections are the primary motivation for Generics in Java.</p>
<p>Let us take a look at some substitution rules. The following are some legal assignments:</p>
<pre><span style="font-family:'Courier New',courier,monospace;">List&lt;Integer&gt; li = <span class="Keyword">new</span> ArrayList&lt;Integer&gt;();
Collection&lt;Integer&gt; ci = <span class="Keyword">new</span> LinkedList&lt;Integer&gt;();
Collection&lt;Integer&gt; cs = <span class="Keyword">new</span> HashSet&lt;Integer&gt;();
List lst = <span class="Keyword">new</span> ArrayList&lt;Number&gt;();
List&lt;Integer&gt; li = <span class="Keyword">new</span> ArrayList();<span class="InlineComment">//warning</span>

</span></pre>
<p>Here is the substitution principle for collections, (Rule 1) RHS of the assignment should contain a Collection implementation compatible with that of LHS and generified with the same type as that of LHS. The last assignment two assignments are valid, these are allowed to provide compatibility of non-generic (prior to Java 5) code with the new generic approach and vice versa. But, if you compile your code with -Xlint:unchecked option, the last assignment results in a unchecked conversion warning. (Rule 2) Do not ignore such compilation warnings, as they indicate your code to be unsafe (could break at runtime with ClassCastExceptions).</p>
<pre><span style="font-family:'Courier New',courier,monospace;">List&lt;String&gt; ls = <span class="Keyword">new</span> ArrayList&lt;String&gt;();<span class="InlineComment">//1 </span>
ls.add(<span class="String">"abc"</span>);<span class="InlineComment">//2 </span>
ls.add(<span class="String">"xyz"</span>);<span class="InlineComment">//3 </span>
Iterator its = ls.listIterator();<span class="InlineComment">//4 </span>
<span class="Statement">while</span>(its.next()) {<span class="InlineComment">//5 </span>
    String s = its.next();<span class="InlineComment">//6 </span>
    System.out.println(<span class="String">"Element: "</span>+s);
}

</span></pre>
<p>Does this compile? No, Iterator is not a generic type and hence the assignment of iterator&#8217;s element to the String &#8216;s&#8217; (line 6) fails with a compilation error. Basically, in line 4 we lost the type information while obtaining the iterator and so we need an explicit cast here. Hence, you need to make the Iterator parameterized with String type to avoid the explicit cast.</p>
<pre><span style="font-family:'Courier New',courier,monospace;">Iterator&lt;String&gt; its = ls.listIterator();<span class="InlineComment">//4</span>

</span></pre>
<p>(Rule 3) When you get an iterator, keySet, entrySet or values from a collection, assign to an appropriate parameterized type as shown above. This is because, these methods are modified to return their corresponding generic types to benifit no-cast code. Most of the Java 5 aware IDEs can do this job for you automatically, rely on them.</p>
<p>The following assignments are invalid:</p>
<pre><span style="font-family:'Courier New',courier,monospace;">Set&lt;String&gt; ss = <span class="Keyword">new</span> HashSet&lt;Integer&gt;();<span class="InlineComment">//Incompatible Types</span>
List&lt;Object&gt; lo = <span class="Keyword">new</span> ArrayList&lt;String&gt;();<span class="InlineComment">//compile-time error</span>

</span></pre>
<p>Though String is a subtype of Object, the second assignment is not allowed. Collection of Objects is a bigger set comprising of elements of various types (Strings, Integers, Cats, Dogs etc.), but a Collection of Strings strictly contains Strings and both of these cannot be equated (Rule 4). In programmatic sense if this were allowed, we would end up adding objects of any type to a List of Strings, defying the purpose of generics and hence this is not allowed.</p>
<p>Well, with the above restriction, how would you implement a method that accepts a collection of any type, iterate over it and print the elements? For such purposes, Wildcards are introduced for generic types to represent unknown collections.</p>
<p><span style="font-size:1.2em;">Wildcards</span><br />
We know that Object[] is the supertype of all arrays, similarly Collection&lt;?&gt; is the supertype of all generic collections which is pronounced as &#8220;Collection of unknown&#8221;. (Note: Collection&lt;?&gt; represents List&lt;?&gt;, ArrayList&lt;?&gt;, HashSet&lt;?&gt; etc. And Collection&lt;?&gt; is only a reference type and you cannot instantiate it, i.e. new ArrayList&lt;?&gt;() or new HashSet&lt;?&gt;() is not allowed.) (Rule 5) Collections parameterized with wildcards cannot be instantiated.</p>
<p>Using Collection&lt;?&gt; we can implement the iterate and print method as shown below.</p>
<pre><span style="font-family:'Courier New',courier,monospace;"><span class="Modifier">public</span> <span class="Type">void</span> printElements(Collection&lt;?&gt; c) {
    <span class="Statement">for</span>(Object o : c) {
        System.out.println(o);
    }
}
...
List&lt;String&gt; ls = <span class="Keyword">new</span> ArrayList&lt;String&gt;();
List&lt;Cat&gt; lc = <span class="Keyword">new</span> ArrayList&lt;Cat&gt;();
...
printElements(ls);
printElements(lc);</span></pre>
<p>Is Collection&lt;?&gt; same as plain old Collection? No, there are lot of differences between the plain old Collection, Collection&lt;?&gt; and Collection&lt;Object&gt;.</p>
<p>The following are the differences between them:</p>
<ul>
<li>Collection&lt;?&gt; is a homogenous collection that represents a family of generic instantiations of Collection (i.e. Collection&lt;String&gt;, Collection&lt;Integer&gt; etc.)</li>
<li>Collection&lt;Object&gt; is a heterogenous collection or a mixed bag that contains elements of all types, close to the plain old Collection but not same</li>
<li>Collection&lt;?&gt; ensures that you don&#8217;t add aribtrary objects, as we do not know the type of the collection (Rule 6)</li>
<li>Collection&lt;?&gt; cannot be treated as a read-only collection, as it allows remove() and clear() operations</li>
<li>You can assign Collection&lt;String&gt; or Collection&lt;Number&gt; to a Collection&lt;?&gt; reference type, but not to a Collection&lt;Object&gt; (Refer to Rule 4)</li>
</ul>
<pre><span style="font-family:'Courier New',courier,monospace;">List&lt;String&gt; list = <span class="Keyword">new</span> ArrayList&lt;String&gt;();
list.add(<span class="String">"Tiger"</span>);
list.add(<span class="String">"Mustang"</span>);
Collection&lt;?&gt; c = list;
Object o = c.get(0); <span class="InlineComment">//returns "Tiger" downcasted to Object</span>
c.contains(<span class="String">"Tiger"</span>); <span class="InlineComment">//returns true</span>
Iterator itr = c.iterator();
<span class="Statement">while</span>(itr.hasNext()) {
    Object o = itr.next();
    System.out.println(o);
}
c.remove(<span class="String">"Mustang"</span>); <span class="InlineComment">//removes "Mustang" from the List</span>
c.add(<span class="String">"Dolphin"</span>); <span class="InlineComment">//compile-time error (as per Rule 6)</span></span></pre>
<p>Collection&lt;?&gt; appears very restrictive as you do not known the type information. When you obtain your elements from this collection you need to work with objects and would sometimes end up in explicit cast. So, strictly encourage Collection&lt;?&gt; when you need no type specific operations (Rule 7). But, there would be very few such use-cases in practice, where as more frequently you may need to perform operations on a base interface and you do not bother about the implementation type. In such cases you can benifit with the &#8216;bounded wildcards&#8217;.</p>
<p><span style="font-size:1.2em;">Bounded wildcards</span><br />
List&lt;? extends Number&gt; is an example of a bounded wildcard. This represents a homogenous List that contains elements that are subtypes of Number. Bounded wildcards only indicate an unknown type which is a subtype of Number.</p>
<pre><span style="font-family:'Courier New',courier,monospace;"><span class="Modifier">public</span> <span class="Type">void</span> addInteger(List&lt;? extends Number&gt; lnum) {
    Number num = lnum.get(0);
    <span class="Type">byte</span> b = num.byteValue();
    lnum.add(<span class="Keyword">new</span> Integer(10));<span class="InlineComment">//not allowed, compile-time error</span>
}</span></pre>
<p>So, we can obtain elements from the collection assuming the type to be a Number. But, you are not allowed to add anything to the collection as we do not know which subtype of Number the collection contains.</p>
<p>Differences between List&lt;Number&gt; and List&lt;? extends Number&gt;:</p>
<ul>
<li>List&lt;Number&gt; is a heterogenous collection of Number objects (i.e. it can contain instances of Integer, Float, Long, etc.)</li>
<li>List&lt;? extends Number&gt; represents a homogenous collection of Number or its subtypes. It is instantiated with any of List&lt;Integer&gt;, List&lt;Float&gt; etc.</li>
</ul>
<p>&#8220;? extends Type&#8221; is known as the upper bound, and we also have &#8220;? super Type&#8221; which is the lower bound where the unknown type denotes a super type of the specified Type. This is rarely useful with collections but could come handy when we define our own generic types.</p>
<p>We&#8217;ll see more about defining generic types, generic methods and type erasure semantics in my next posts.</p>
<script type="text/javascript" src="http://cdn.socialtwist.com/2011021149263/script.js"></script><a class="st-taf" href="http://tellafriend.socialtwist.com:80" onclick="return false;" style="border:0;padding:0;margin:0;"><img alt="SocialTwist Tell-a-Friend" style="border:0;padding:0;margin:0;" src="http://images.socialtwist.com/2011021149263/button.png" onmouseout="STTAFFUNC.hideHoverMap(this)" onmouseover="STTAFFUNC.showHoverMap(this, '2011021149263', 'http%3A%2F%2Fblog.deepincode.com%2F2006%2F12%2Funderstanding-generics-with-collections-2%2F', 'Understanding+Generics+with+Collections')" onclick="STTAFFUNC.cw(this, {id:'2011021149263', link: 'http%3A%2F%2Fblog.deepincode.com%2F2006%2F12%2Funderstanding-generics-with-collections-2%2F', title: 'Understanding+Generics+with+Collections' });"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.deepincode.com/2006/12/understanding-generics-with-collections-2/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Bootstrapping static fields within enums</title>
		<link>http://blog.deepincode.com/2006/12/bootstrapping-static-fields-within-enums/</link>
		<comments>http://blog.deepincode.com/2006/12/bootstrapping-static-fields-within-enums/#comments</comments>
		<pubDate>Fri, 08 Dec 2006 14:51:54 +0000</pubDate>
		<dc:creator>Deepak Anupalli</dc:creator>
				<category><![CDATA[Java5]]></category>

		<guid isPermaLink="false">http://deepjava.wordpress.com/2006/12/08/bootstrapping-static-fields-within-enums/</guid>
		<description><![CDATA[In my earlier post on enums in Java 5, we have seen that static fields cannot be accessed within the enum constructor. With this restriction we could run into few initialization problems discussed below. The other day Rajiv found it difficult to initialize a static cache during enum bootstrap. The following is his enum: public ]]></description>
			<content:encoded><![CDATA[<p style="margin:7.5pt 3.75pt;"><span style="font-size:10.5pt;font-family:'Trebuchet MS';">In my earlier post on <a href="http://deepjava.wordpress.com/2006/11/21/type-safe-enumerations-in-java-50" title="Enums">enums</a> in Java 5, we have seen that static fields cannot be accessed within the enum constructor. With this restriction we could run into few initialization problems discussed below.</span></p>
<p style="margin:7.5pt 3.75pt;"><span style="font-size:10.5pt;font-family:'Trebuchet MS';">The other day Rajiv found it difficult to initialize a static cache during enum bootstrap. The following is his enum:</span></p>
<p><pre>
<span class="Modifier">public</span> <span class="Type">enum</span> Tag {
    KEYWORDS(2, 25, <span class="Keyword">true</span>),
    DATE_CREATED(2, 55, <span class="Keyword">false</span>),
    HEADLINE(2, 105, <span class="Keyword">false</span>),
    …
    <span class="Modifier">private</span> <span class="Type">int</span> recordNo;
    <span class="Modifier">private</span> <span class="Type">int</span> datasetNo;
    <span class="Modifier">private</span> <span class="Type">int</span> isRepeat;

    <span class="Modifier">private</span> Tag(<span class="Type">int</span> recordNo, <span class="Type">int</span> datasetNo, <span class="Type">int</span> isRepeat) {
        <span class="Keyword">this</span>.recordNo = recordNo;
        <span class="Keyword">this</span>.datasetNo = datasetNo;
        <span class="Keyword">this</span>.isRepeat = isRepeat;
    }
    …
    <span class="Modifier">public</span> <span class="Modifier">static</span> Tag getTag(<span class="Type">int</span> recordNo, <span class="Type">int</span> datasetNo) {
        <span class="Statement">for</span>(Tag tag : Tag.values()) { <span class="InlineComment">//$REVIEW$ optimize</span>
            <span class="Statement">if</span>(tag.getRecordNo() == recordNo &amp;&amp; tag.getDatasetNo() == datasetNo){
                <span class="Statement">return</span> tag;
            }
        }
    }
}</pre>
</p>
<p style="margin:7.5pt 3.75pt;"><span style="font-size:10.5pt;font-family:'Trebuchet MS';">Rajiv says, &#8220;Deeps, check my implementation of getTag(int recordNo, int datasetNo). I would have liked to make a static map of (recordNo&lt;&lt;8 + datasetNo) vs Tag to make this method fast. Unfortunately, I cannot access that static map from the constructor.&#8221;</span></p>
<p style="margin:7.5pt 3.75pt;"><span style="font-size:10.5pt;font-family:'Trebuchet MS';">So, he would like to have a static cache of enums for easy retrieval based on their properties. But, the concern is where do we initialize this cache/map? In the discussion following the earlier <a href="http://deepjava.wordpress.com/2006/11/21/type-safe-enumerations-in-java-50/">post</a>, we discussed that &#8220;enums are initialized before any static initializers are run&#8221;. Bang! We can initialize this cache in a static block as shown below (actually derived from Neal Gafter&#8217;s discussion on forum).</span></p>
<p><pre>
<span class="Modifier">public</span> <span class="Type">enum</span> Tag {
    KEYWORDS(2, 25, <span class="Keyword">true</span>),
    DATE_CREATED(2, 55, <span class="Keyword">false</span>),
    HEADLINE(2, 105, <span class="Keyword">false</span>),
    …
    <span class="Modifier">private</span> <span class="Modifier">static</span> Map&lt;Integer, Tag&gt; cache;
    <span class="Modifier">static</span> {
        cache = <span class="Keyword">new</span> HashMap&lt;Integer, Tag&gt;();
        <span class="Statement">for</span>(Tag tag : values()) {
            <span class="Type">int</span> key = tag.getRecordNo()&lt;&lt;8 + tag.getDatasetNo();
            cache.put(key, tag);
        }
    }
    …
    <span class="Modifier">public</span> <span class="Modifier">static</span> Tag getTag(<span class="Type">int</span> recordNo, <span class="Type">int</span> datasetNo) {
        <span class="Type">int</span> key = recordNo&lt;&lt;8 + datasetNo;
        <span class="Statement">return</span> cache.get(key);
    }
}</pre>
</p>
<p><span style="font-size:10.5pt;font-family:'Trebuchet MS';">Enum constants are already constructed, by the time static block initializer is run. This is a ridiculous pattern to follow though, when you need to boot strap your static fields within enums.</span></p>
<script type="text/javascript" src="http://cdn.socialtwist.com/2011021149263/script.js"></script><a class="st-taf" href="http://tellafriend.socialtwist.com:80" onclick="return false;" style="border:0;padding:0;margin:0;"><img alt="SocialTwist Tell-a-Friend" style="border:0;padding:0;margin:0;" src="http://images.socialtwist.com/2011021149263/button.png" onmouseout="STTAFFUNC.hideHoverMap(this)" onmouseover="STTAFFUNC.showHoverMap(this, '2011021149263', 'http%3A%2F%2Fblog.deepincode.com%2F2006%2F12%2Fbootstrapping-static-fields-within-enums%2F', 'Bootstrapping+static+fields+within+enums')" onclick="STTAFFUNC.cw(this, {id:'2011021149263', link: 'http%3A%2F%2Fblog.deepincode.com%2F2006%2F12%2Fbootstrapping-static-fields-within-enums%2F', title: 'Bootstrapping+static+fields+within+enums' });"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.deepincode.com/2006/12/bootstrapping-static-fields-within-enums/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Type Safe Enumerations in Java 5.0</title>
		<link>http://blog.deepincode.com/2006/11/type-safe-enumerations-in-java-50/</link>
		<comments>http://blog.deepincode.com/2006/11/type-safe-enumerations-in-java-50/#comments</comments>
		<pubDate>Tue, 21 Nov 2006 17:12:33 +0000</pubDate>
		<dc:creator>Deepak Anupalli</dc:creator>
				<category><![CDATA[Java5]]></category>

		<guid isPermaLink="false">http://deepjava.wordpress.com/2006/11/21/type-safe-enumerations-in-java-50/</guid>
		<description><![CDATA[The new enum construct in Java 5.0 is used to define enumerations. Enumerations are not new to programming languages, they existed in C, C++, SmallTalk etc. In Java 5.0 they had to be introduced to overcome safety and ease of use concerns in using the earlier enumeration approaches. Let us take a look at how ]]></description>
			<content:encoded><![CDATA[<p>
  The new <strong>enum</strong> construct in Java 5.0 is used to define enumerations. Enumerations are not new to programming languages, they existed in C, C++, SmallTalk etc. In Java 5.0 they had to be introduced to overcome safety and ease of use concerns in using the earlier enumeration approaches. Let us take a look at how we used to define enumeration constants prior to Java 5.0.
</p>
<p>
  <span style="font-size:1.2em;">Type Safety concern for enumerations</span><br />
  <br />
  In programming sense, enumerations can be treated as just a sequence of integers. Let us define an enumeration that represents a sample of Colors (RED, BLUE, YELLOW, GREEN, ORANGE &amp; PURPLE).
</p>
<pre>
<code>
public interface Colors {
    final int RED=1, BLUE=2, YELLOW=3, GREEN=4, ORANGE=5, PURPLE=6;
}

public interface Shape {
    void applyColor(int color);
    ...
}

Shape box = new Rectangle();//Rectangle implements Shape
box.applyColor(Colors.RED);
</code>
</pre>
<p>
  Whereever we need a color, we use the constants defined in Colors. But, what if an integer that is not defined for any of the constants is passed to the applyColor() method? Say <tt>box.applyColor(8)</tt>, It fails. <tt>Shape.applyColor()</tt> method takes any integer, there is no &quot;Type Safety&quot;.
</p>
<p>
  So, it is not true to say enumerations are a sequence of integers. Enumerations should be treated as a separate type. Let us re-define the enumeration to take care of Type Safety.
</p>
<p>
  <span style="font-size:1.2em;">Enumerated Pattern before Java 5</span><br />
  <br />
  Prior to Java 5 release, enumerations were defined using the Enumerated pattern described in the book, <a href="http://java.sun.com/docs/books/effective/index.html">Effective Java</a>. Enumerated pattern takes care of type safety.
</p>
<pre>
<code>
public final class Color
{
    public static final Color RED = new Color(1);
    public static final Color BLUE = new Color(2);

    private int color;    //ensures singleton and no instantiations

    private Color(int color) { this.color = color; }
    public int getColor() { return color; }

    //overridden to give meaningful values
    public String toString() {
        switch (getColor()) {
            case 1: return &quot;RED&quot; break;
            ...
        }
    }

    public boolean equals(Object obj) { return this == obj;}
}

public interface Shape {
    //The method takes a Color type, not integer
    void applyColor(Color color);
}
</code>
</pre>
<p>
  This enumerated pattern ensures that the <tt>Color</tt> type is Singleton and provides type safe enumerated constants RED, BLUE, YELLOW, GREEN etc. The <tt>toString()</tt> method is overriden to provide meaningful information when the constants are printed and the <tt>equals()</tt> method checks the reference equality of enumerated types, as these are singleton instances. Is this all enough to define a complete enumerated type? No.
</p>
<p>
  <span style="font-size:1.2em;">Disadvantages of the above enumerated pattern</span><br />
  <br />
  The enumerated pattern approach has the following drawbacks:
</p>
<ul>
<li>Enumerated types are not Serializable and Comparable by default. In case, if we make them Serializable,<br />
  Serialization of Color creates a new instance of the same <tt>Color</tt>. The <tt>equals()</tt> method fails to identify the equality of a serialized and a non-serialized Color. (Ofcourse, we can fix this by custom serialization of enumerated types. But, this leads to writing more boiler plate code for each enumerated type)
  </li>
<li>Color instances cannot be directly used in the switch-case statements, instead you need to use the color value</li>
<li>If a new color is added between existing constants or if the order of Colors is changed, clients must be<br />
  recompiled. (a.k.a Brittleness)
  </li>
<li>No support for iterating over the defined enumerated constants
  </li>
</ul>
<p>
  <span style="font-size:1.2em;">Java 5 enum</span><br />
  <br />
  enum provides a cleaner syntax to define enumerations in Java. And also overcomes all the drawbacks set by the earlier Enumerated pattern.
</p>
<ul>
<li>enums are type safe
  </li>
<li>enums provide default implementation for <tt>toString(), equals(), hashCode()</tt> methods (Umm.. no extra work)
  </li>
<li>enums are Comparable and Serializable by default
  </li>
<li>enums are allowed to be used in switch-case statements
  </li>
<li>enums are allowed to implement interfaces
  </li>
<li>Adding new enum constants, does not require re-compilation of the client code
  </li>
<li>A static <tt>values()</tt> method is provided that returns an array of defined enumerated constants
  </li>
</ul>
<p>
  Let us define the Color enumeration using Java 5 enum construct.
</p>
<pre>
<code>
public enum Color {
    RED, BLUE, YELLOW, GREEN, ORANGE, PURPLE
}
</code>
</pre>
<p>
  The enumerated types RED, BLUE, YELLOW etc. are of type Color. <tt>java.lang.Enum</tt> is the supertype of all enums and the Color enum implicitly extends <tt>java.lang.Enum</tt>. <tt>java.lang.Enum</tt> provides implementation for <tt>equals(), toString(), and hashCode()</tt> methods and it implements Serializable and Comparable interfaces. Enums are full-fledged java classes and can have arbitrary methods and fields. Enums can implement interfaces. Enums can have constructors and they take arguments in the declaration as shown below.
</p>
<pre>
<code>
public enum Color {
    RED(625, 740),
    ORANGE(590, 625),
    YELLOW(565, 590),
    ...

    //Electro-magnetic Spectrum wavelength in nm
    int startWavelength;
    int endWavelength;

    Color(start, end) {
        this.startWavelength = start;
        this.endWavelength = end;
    }

    public int getStartWavelength() { return startWavelength; }
    public int getEndWavelength() { return endWavelength; }

    public static void main(String[] args) {
        System.out.println(&quot;Red color&#039;s wavelength range, &quot;
            + RED.getStartWavelength()+&quot; ~ &quot;+RED.getEndWavelength());
    }
}
</code>
</pre>
<p>
  If the Enumerated types have any attributes, a constructor is used to associate these attributes and the Getter methods expose these attributes.
</p>
<p>
  <span style="font-size:1.2em;">Constant specific methods</span><br />
  <br />
  If the implementation of methods vary for each Constant, then you can implement the methods specific to a constant.
</p>
<pre>
<code>
public enum Color {
    RED { public Color complimentary() { return GREEN; }},
    BLUE { public Color complimentary() { return ORANGE; }},
    YELLOW { public Color complimentary() { return PURPLE; }},
    ...

    public abstract Color complimentary();
}
</code>
</pre>
<p>
  Each color has its own complementary color and to implement this we can use constant specific methods to return the complementary color. The method <tt>complementary()</tt> has to be either defined as an abstract method within Color enum or could be a method in one of the implemented interfaces.
</p>
<p>
  <span style="font-size:1.2em;">Restrictions on enum types</span><br />
  <br />
  Though enum types are full-fledged classes, the following are not allowed with enums:
</p>
<ul>
<li>enums cannot be subclassed
  </li>
<li>enums cannot have public constructor
  </li>
<li>enums are not allowed to be instantiated (using new)
  </li>
<li>enums cannot be cloned
  </li>
</ul>
<p>
  All of these are enforced during compile-time.
</p>
<p>
  <span style="font-size:1.2em;">Serialization of enums</span><br />
  <br />
  Serialization mechanism ensures that new enum instances are not created on serialization and de-serialization (ensuring singleton behaviour). In a distributed environment when an enum is serialized from one JVM to another JVM, enum&#039;s state is not serialized. Hence, it is not encouraged to have state with enums which is updated by the applications. You can only have constant attributes that are initialized by the constructor.
</p>
<p>
  <span style="font-size:1.2em;">Collections built for enums</span><br />
  <br />
  <tt>java.util.EnumMap</tt> and <tt>java.util.EnumSet</tt> are the collections added for use with enum types. They provide a compact and efficient implementation for enum types. These collections are not synchronized and when used in multi-threaded environment, applications should take care of synchronizing the operations on the collection. EnumMap and EnumSet are homogenous collections of the same enum type. They cannot be used to operate on different enum types at the same time.<br />
  
</p>
<pre>
<code>
public enum Color {
    RED, BLUE, YELLOW, GREEN, ORANGE, PURPLE;

    public static EnumSet&lt;Color&gt; getPrimaryColors() {
        return EnumSet.of(RED, BLUE, YELLOW);
    }

    public static EnumSet&lt;Color&gt; getSecondaryColors() {
        return EnumSet.complementOf(getPrimaryColors());
    }

    public static void main(String[] args) {
        System.out.println(&quot;Primary Colors: &quot;+Color.getPrimaryColors());
        System.out.println(&quot;Secondary Colors: &quot;+Color.getSecondaryColors());
        System.out.println(&quot;Universe: &quot;+EnumSet.allOf(Color.class));
    }
}
</code>
</pre>
<p>
  <span style="font-size:1.2em;">Few gotchas about enums</span><br />
  <br />
  However, there are few things which could probably be improved in the coming versions of Java.
</p>
<ul>
<li>Currently null can be passed as a method parameter or assigned where an enum is expected. A compile-time verification for null enum assignment would probably avoid all those extra null checks that we need to incorporate in our code.
  </li>
<li>Static fields within enums cannot be accessed in its constructor. But, static methods are allowed to be invoked. The compiler enforces verification only for static fields and not methods.
  </li>
<li>However, enum constructors are invoked before static initialization is performed and hence the static fields would not be initialized. So, if you invoke static methods from the constructor which inturn access static fields, they would all be un-initialized.
  </li>
</ul>
<p>
  <span style="font-size:1.2em;">Enum syntax</span>
</p>
<pre>
<code>
public enum &lt;your_enum&gt; {
    &lt;enum_constant1&gt; (&lt;constructor_params&gt;) {
        &lt;anonymous_class_declaration&gt;
    },
    &lt;enum_constant2&gt; (...) {...},
    ...;
    //enum constructor [optional]
    &lt;your_enum&gt; (&lt;constructor_param_defs&gt;) {
        //static fields within enum cannot be accessed
    }
    &lt;class body&gt; [optional]
}
</code>
</pre>
<script type="text/javascript" src="http://cdn.socialtwist.com/2011021149263/script.js"></script><a class="st-taf" href="http://tellafriend.socialtwist.com:80" onclick="return false;" style="border:0;padding:0;margin:0;"><img alt="SocialTwist Tell-a-Friend" style="border:0;padding:0;margin:0;" src="http://images.socialtwist.com/2011021149263/button.png" onmouseout="STTAFFUNC.hideHoverMap(this)" onmouseover="STTAFFUNC.showHoverMap(this, '2011021149263', 'http%3A%2F%2Fblog.deepincode.com%2F2006%2F11%2Ftype-safe-enumerations-in-java-50%2F', 'Type+Safe+Enumerations+in+Java+5.0')" onclick="STTAFFUNC.cw(this, {id:'2011021149263', link: 'http%3A%2F%2Fblog.deepincode.com%2F2006%2F11%2Ftype-safe-enumerations-in-java-50%2F', title: 'Type+Safe+Enumerations+in+Java+5.0' });"/></a>]]></content:encoded>
			<wfw:commentRss>http://blog.deepincode.com/2006/11/type-safe-enumerations-in-java-50/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
	</channel>
</rss>

