<?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>Ankit Virparia &#187; generics</title>
	<atom:link href="http://ankit.co/tag/generics-2/feed" rel="self" type="application/rss+xml" />
	<link>http://ankit.co</link>
	<description>A Programmer, Designer and Trainer</description>
	<lastBuildDate>Sun, 11 May 2014 04:15:47 +0000</lastBuildDate>
	<language>en-US</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.0.38</generator>
	<item>
		<title>Bounded Type Generic Parameters</title>
		<link>http://ankit.co/tutorials/java-tutorials/generics/bounded-type-generic-parameters?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=bounded-type-generic-parameters</link>
		<comments>http://ankit.co/tutorials/java-tutorials/generics/bounded-type-generic-parameters#comments</comments>
		<pubDate>Tue, 08 Jan 2013 00:35:30 +0000</pubDate>
		<dc:creator><![CDATA[Ankit Virparia]]></dc:creator>
				<category><![CDATA[Generics]]></category>
		<category><![CDATA[bound type]]></category>
		<category><![CDATA[generics]]></category>

		<guid isPermaLink="false">http://ankit.co/?p=231</guid>
		<description><![CDATA[<p>In a simple terms, Generic provides you a freedom to pass the &#8220;Type&#8221; parameter when we create the object of such class. Now, Assume that: A Generic class is written a developer and some other developers are gonna use the same(Your .class file). And you also want to restrict the other developers to pass some [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/generics/bounded-type-generic-parameters">Bounded Type Generic Parameters</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></description>
				<content:encoded><![CDATA[<p>In a simple terms, Generic provides you a freedom to pass the &#8220;Type&#8221; parameter when we create the object of such class.</p>
<p>Now, Assume that: A Generic class is written a developer and some other developers are gonna use the same(Your .class file). And you also want to restrict the other developers to pass some special kinds of types that are allowed as a type parameter. I mean &#8211; You don&#8217;t want to accept anything. Your class should accept only certain predefined things. How can we do that? The answer to this is &#8220;Bounded Type Generic Parameters&#8221;.</p>
<p>To declare a bounded type parameter, write the type parameter&#8217;s name, followed by the extends keyword, followed by its upper(parent) bound(class).</p>
<h3>Example:</h3>
<p><strong>We need a generic method of a generic class which only accepts three Comparable objects and return the largest object.</strong></p>
<pre class="brush: java; title: ; notranslate">
public class MaximumTest
{
   // determines the largest of three Comparable objects
   public static &lt;T extends Comparable&lt;T&gt;&gt; T maximum(T x, T y, T z)
   {                      
      T max = x; // assume x is initially the largest       
      if ( y.compareTo( max ) &gt; 0 ){
         max = y; // y is the largest so far
      }
      if ( z.compareTo( max ) &gt; 0 ){
         max = z; // z is the largest now                 
      }
      return max; // returns the largest object   
   }
   public static void main( String args[] )
   {
      System.out.printf( &quot;Max of %d, %d and %d is %d\n\n&quot;, 3, 4, 5, maximum( 3, 4, 5 ) );

      System.out.printf( &quot;Maxm of %.1f,%.1f and %.1f is %.1f\n\n&quot;, 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) );

      System.out.printf( &quot;Max of %s, %s and %s is %s\n&quot;,&quot;pear&quot;, &quot;apple&quot;, &quot;orange&quot;, maximum( &quot;pear&quot;, &quot;apple&quot;, &quot;orange&quot; ) );
   }
}
</pre>
<p><strong>Output:</strong></p>
<p><a class="highslide"  onclick="return hs.expand(this)" href="../../../images/bounded_type.jpg" rel="attachment"><img class="size-full aligncenter" alt="Generics Bounded Type" src="../../../images/bounded_type_400.jpg" /></a></p>
<p><strong>Note: </strong> Integer, Float, Boolean, String all the wrapper classes are implementing Comparable interface. That&#8217;s why maximum() method is accepting our arguments. </p>
<p>Let&#8217;s test it by passing StringBuffer objects which are not comparable because StringBuffer do not implements Comparable interface.</p>
<pre class="brush: java; title: ; notranslate">
public class MaximumTest
{
   // determines the largest of three Comparable objects
   public static &lt;T extends Comparable&lt;T&gt;&gt; T maximum(T x, T y, T z)
   {                      
      T max = x; // assume x is initially the largest       
      if ( y.compareTo( max ) &gt; 0 ){
         max = y; // y is the largest so far
      }
      if ( z.compareTo( max ) &gt; 0 ){
         max = z; // z is the largest now                 
      }
      return max; // returns the largest object   
   }
   public static void main( String args[] )
   {
	   StringBuffer s1 = new StringBuffer(&quot;Test&quot;);
	   StringBuffer s2 = new StringBuffer(&quot;Test2&quot;);
	   StringBuffer s3 = new StringBuffer(&quot;Test3&quot;);
       maximum( s1, s2, s3 );
   }
}
</pre>
<p><strong>Error:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/sb_boundType.jpg" rel="attachment"><img class="size-full aligncenter" alt="Generics Bounded Type output" src="../../../images/sb_boundType_400.jpg" /></a></p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/generics/bounded-type-generic-parameters">Bounded Type Generic Parameters</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ankit.co/tutorials/java-tutorials/generics/bounded-type-generic-parameters/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Basic Programs on Generics</title>
		<link>http://ankit.co/tutorials/java-tutorials/generics/basic-programs-on-generics?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=basic-programs-on-generics</link>
		<comments>http://ankit.co/tutorials/java-tutorials/generics/basic-programs-on-generics#comments</comments>
		<pubDate>Mon, 07 Jan 2013 23:11:11 +0000</pubDate>
		<dc:creator><![CDATA[Ankit Virparia]]></dc:creator>
				<category><![CDATA[Generics]]></category>
		<category><![CDATA[examples]]></category>
		<category><![CDATA[generics]]></category>

		<guid isPermaLink="false">http://ankit.co/?p=218</guid>
		<description><![CDATA[<p>Generic Functionality Generics introduced the concept of type variable. A type variable is an unqualified identifier as per the Java Language Specification, Which can be used in following ways: Generic class declarations Generic interface declarations Generic method declarations Generic constructor declarations. Above code demonstrates the use of Generic class, constructor and method. Here we are [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/generics/basic-programs-on-generics">Basic Programs on Generics</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></description>
				<content:encoded><![CDATA[<h2>Generic Functionality</h2>
<p>Generics introduced the concept of type variable. A type variable is an unqualified identifier as per the Java Language Specification, Which can be used in following ways:</p>
<ul>
<li>Generic class declarations</li>
<li>Generic interface declarations</li>
<li>Generic method declarations</li>
<li>Generic constructor declarations.</li>
</ul>
<pre class="brush: java; title: ; notranslate">
class genericsDemo
{
	public static void main(String[] s)
	{
		test&lt;Integer&gt; t = new test&lt;Integer&gt;(5);
		int i = t.getI();       // No need to type cast!
		System.out.println(i);

		test&lt;String&gt; ts = new test&lt;String&gt;(&quot;This is demo.&quot;);
		String is = ts.getI();   // No need to type cast!
		System.out.println(is);
		
		xyz o = new xyz(7);
		test&lt;xyz&gt; txyz = new test&lt;xyz&gt;(o);
		xyz newo = txyz.getI();   // No need to type cast!
		System.out.println(newo);
	}	
}

 
class test&lt;T&gt;         // Generic class
{
	private T i;
	test(T i)     // Generic Constructor
	{
		this.i = i;	
	}	
	T getI()     // Generic Method
	{
		return i;	
	}
}


class xyz
{
	int x;
	xyz(int x)
	{
		this.x = x;
	}
	
	public String toString()
	{
		return &quot;Value of X is: &quot;+x;
	}
}
</pre>
<p>Above code demonstrates the use of Generic class, constructor and method. Here we are learning one more thing: It&#8217;s not a compulsion that we can only pass wrapper class objects as generic variable. A custom/User defined class&#8217;s object can also be passed as we did with: &#8220;xyz&#8221; class.</p>
<p><strong>Output: </strong></p>
<p><a class="highslide"  onclick="return hs.expand(this)" href="../../../images/generic.jpg" rel="attachment"><img class="size-full aligncenter" alt="Generics Basic" src="../../../images/generic_400.jpg" /></a></p>
<hr/>
<h3>Example on Generic Method</h3>
<pre class="brush: java; title: ; notranslate">
public class GenericMethodTest
{
   // generic method printArray                         
   public static &lt;E&gt; void printArray( E[] inputArray )
   {
      // Display array elements              
         for ( E element : inputArray )
         {        
            System.out.printf( &quot;%s &quot;, element );
         }
         System.out.println();
    }

    public static void main( String args[] )
    {
        // Create arrays of Integer, Double and Character
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

        System.out.println( &quot;Array integerArray contains:&quot; );
        printArray( intArray  ); // pass an Integer array

        System.out.println( &quot;\nArray doubleArray contains:&quot; );
        printArray( doubleArray ); // pass a Double array

        System.out.println( &quot;\nArray characterArray contains:&quot; );
        printArray( charArray ); // pass a Character array
    } 
}
</pre>
<p><strong>Output: </strong></p>
<p><a class="highslide"  onclick="return hs.expand(this)" href="../../../images/genericMethod.jpg" rel="attachment"><img class="size-full aligncenter" alt="Generics Basic" src="../../../images/genericMethod_400.jpg" /></a></p>
<hr/>
<h3>Example on Generic Interface</h3>
<pre class="brush: java; title: ; notranslate">
interface MinMax&lt;T extends Comparable&lt;T&gt;&gt; 
{
	T min();
	T max();
}
// Now, implement MinMax
class MyClass&lt;T extends Comparable&lt;T&gt;&gt; implements MinMax&lt;T&gt; 
{
	T[] vals;
	MyClass(T[] o) 
	{ 
		vals = o; 
	}
	// Return the minimum value in vals.
	public T min() 
	{
		T v = vals[0];
		for(int i=1; i &lt; vals.length; i++)
		if(vals[i].compareTo(v) &lt; 0) v = vals[i];
		return v;
	}
	// Return the maximum value in vals.
	public T max() 
	{
		T v = vals[0];
		for(int i=1; i &lt; vals.length; i++)
		if(vals[i].compareTo(v) &gt; 0) v = vals[i];
		return v;
	}
}
class GenIFDemo 
{
	public static void main(String args[]) 
	{
		Integer inums[] = {3, 6, 2, 8, 6 };
		Character chs[] = {'b', 'r', 'p', 'w' };
		MyClass&lt;Integer&gt; iob = new MyClass&lt;Integer&gt;(inums);
		MyClass&lt;Character&gt; cob = new MyClass&lt;Character&gt;(chs);
		System.out.println(&quot;Max value in inums: &quot; + iob.max());
		System.out.println(&quot;Min value in inums: &quot; + iob.min());
		System.out.println(&quot;Max value in chs: &quot; + cob.max());
		System.out.println(&quot;Min value in chs: &quot; + cob.min());
	}
}
</pre>
<p><strong>Output: </strong></p>
<p><a class="highslide"  onclick="return hs.expand(this)" href="../../../images/genIfDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Generics Basic" src="../../../images/genIfDemo_400.jpg" /></a></p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/generics/basic-programs-on-generics">Basic Programs on Generics</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ankit.co/tutorials/java-tutorials/generics/basic-programs-on-generics/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introduction to Generics</title>
		<link>http://ankit.co/tutorials/java-tutorials/generics/introduction-to-generics?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=introduction-to-generics</link>
		<comments>http://ankit.co/tutorials/java-tutorials/generics/introduction-to-generics#comments</comments>
		<pubDate>Mon, 07 Jan 2013 16:34:03 +0000</pubDate>
		<dc:creator><![CDATA[Ankit Virparia]]></dc:creator>
				<category><![CDATA[Generics]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[What is]]></category>

		<guid isPermaLink="false">http://ankit.co/?p=211</guid>
		<description><![CDATA[<p>What is Generics? Till now whatever classes/methods/constructors/variables we have created were datatype specific i.e. having a fixed datatype which was decided by the owner of the class and cannot be changed once the class is compiled. For example, Above method takes an int value as a parameter which do not support any other datatype. But [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/generics/introduction-to-generics">Introduction to Generics</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></description>
				<content:encoded><![CDATA[<h3>What is Generics?</h3>
<p>Till now whatever classes/methods/constructors/variables we have created were datatype specific i.e. having a fixed datatype which was decided by the owner of the class and cannot be changed once the class is compiled. For example,</p>
<pre class="brush: java; title: ; notranslate">
public void disp(int x)
{
}
</pre>
<p>Above method takes an int value as a parameter which do not support any other datatype. But let&#8217;s say now we are considering a scenario where by there are 2 developers: 1) developer1 and 2) developer2.</p>
<p>Developer1 has written following class which is used by developer2 to find the maximum number from the given set of numbers as discussed below:</p>
<p><strong>Developer1 Wrote:</strong></p>
<pre class="brush: java; title: ; notranslate">
public class findMax
{
	public int maxFrom(int[] arr)
	{	
		int max = 0;
		//code to find max out of given arr and assing it to max variable
		return max;
	
	}
}
</pre>
<p>Now, Developer2 wants to use the class which is created by developer1. Remember that developer2 cannot modify the class <strong>findMax</strong> which is created by developer1.<br />
<strong>Developer2 Wrote:</strong></p>
<pre class="brush: java; title: ; notranslate">
public class abc
{
	public static void main(String[] args)
	{	
		int[] iarr = {1,2,3,4,5,6,7,8,9,0};
		findMax fm = new findMax();
		int max = fm.maxFrom(iarr);
	}
}
</pre>
<p>Correct! Developer2 can use it easily by creating an object and doing a method call.<br />
<strong>Then what is the problem? </strong>Problem is when the developer2 want to find max number out of given set of float numbers. He is planning to pass float[] as an argument and wants a float value back. But there is no such method available in the class findMax which is developed by developer1. </p>
<p>Let&#8217;s say on special request of developer2 even if developer1 agrees to add a overloaded method then that can be said as a temporary solution!<br />
<strong>Developer1 Wrote:</strong></p>
<pre class="brush: java; title: ; notranslate">
public class findMax
{
	public int maxFrom(int[] arr)
	{	
		int max = 0;
		//code to find max out of given arr and assing it to max variable
		return max;
	
	}
	public float maxFrom(float[] arr)
	{	
		float max = 0;
		//code to find max out of given arr and assing it to max variable
		return max;
	
	}

}
</pre>
<p>It&#8217;s a temporary solution because it cannot be said that there won&#8217;t be any future requirement (of developer2) to find a maximum double value out of the given double[]. In that case we have to write one more overloaded method! But Howmany? Whatever number of overloaded method developer1 writes are fixed while writing the class. So, developer2 will be always dependent on developer1! So, This is the problem which can be resolved by the use of Generics&#8230;</p>
<h2>Generics</h2>
<p>Generics is a Java feature that was introduced with Java SE 5.0. It&#8217;s an easy to use feature and many resources are available for Generics but lot many developers face problem in understanding generics concept in java. Anyway, Let&#8217;s start!</p>
<p><strong>Variable:</strong><br />
A variable is normally used by a developer to store some literals right? But lets say a variable which holds the java class/wrapper class that can be said as a generic variable.</p>
<p><strong>How developer1 can write a Generic calss &#8220;findMax&#8221;?</strong><br />
<strong>Developer1 Wrote:</strong></p>
<pre class="brush: java; title: ; notranslate">
public class findMax&lt;T&gt;
{
	public T maxFrom(T[] arr)
	{	
		T max = 0;
		//code to find max out of given arr and assing it to max variable
		return max;
	
	}
}
</pre>
<p>So, As shown in the code above our method maxForm() not takes T type of array as an argument and returns T type of data. Here &#8220;T&#8221; is the variable which will hold the datatype and that can be decided by develope2! How?</p>
<p><strong>Developer2 Wrote:</strong></p>
<pre class="brush: java; title: ; notranslate">
public class abc
{
	public static void main(String[] args)
	{	
		Integer[] iarr = {1,2,3,4,5,6,7,8,9,0};
		findMax&lt;Integer&gt; fm = new findMax&lt;Integer&gt;();
		int max = fm.maxFrom(iarr);
		System.out.println(max);
	}
}
</pre>
<p>Note: Make sure you do not pass any datatype as a generic value, Which is not allowed. Here I passed Integer instead of int whereby Integer is the wrapper class of int datatype.</p>
<p>Full Program by Developer1:</p>
<pre class="brush: java; title: ; notranslate">
import java.util.*;
class findMax&lt;T&gt;
{
	public T maxFrom(T[] arr)
	{	
		T max = arr[0];

		for(int i=0;i&lt;arr.length-1;i++)
		{
			Comparable one = (Comparable)arr[i];
			Comparable two = (Comparable)arr[i+1];

			if(one.compareTo(two) &lt; 0)
			{
				max = arr[i+1];
			}	
		}
		//code to find max out of given arr and assing it to max variable
		return max;
	
	}
}
</pre>
<p>Developer2 may use it with different different datatypes by using appropriate wrapper class.</p>
<pre class="brush: java; title: ; notranslate">
public class abc
{
	public static void main(String[] args)
	{	
		Integer[] iarr = {1,2,3,4,5,6,7,8,9,0};
		findMax&lt;Integer&gt; fm = new findMax&lt;Integer&gt;();
		int max = fm.maxFrom(iarr);
		System.out.println(max);

		Float[] farr = {1.2,2.3,3.4,4.5,5.6,6.9,7.2,8.1,9.0,0.2};
		findMax&lt;Float&gt; ffm = new findMax&lt;Float&gt;();
		float fmax = ffm.maxFrom(farr);
		System.out.println(fmax);

	}
}
</pre>
<p>Again, A major change that you will find is: Comparable? What is that? Ammm&#8230; Comparable is an interface which belongs to java.util package which can be used to compare any object. If we need to compare a normal variable, we might have used <, >, == operators but in our case developer1 (who is writing the logic) does not know anything about what kind of value T will hold. So, We are casting our array indexes to Comparable and comparing it so that we can find the maximum value.</p>
<p>Hope you have understood what is Generics! Write a comment or ask a question. Feel free to contact me.</p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/generics/introduction-to-generics">Introduction to Generics</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ankit.co/tutorials/java-tutorials/generics/introduction-to-generics/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
