<p>I thought I'd offer this softball to whomever would like to hit it out of the park. What are generics, what are the advantages of generics, why, where, how should I use them? Please keep it fairly basic. Thanks.</p>

[{'answer_id': 77652, 'author': 'Mitchel Sellers', 'author_id': 13279, 'author_profile': 'https://Stackoverflow.com/users/13279', 'pm_score': 2, 'selected': False, 'text': "<p>Generics allow you to create objects that are strongly typed, yet you don't have to define the specific type.  I think the best useful example is the List and similar classes.  </p>\n\n<p>Using the generic list you can have a List List List whatever you want and you can always reference the strong typing, you don't have to convert or anything like you would with a Array or standard List.</p>\n"}, {'answer_id': 77662, 'author': 'Darren Kopp', 'author_id': 77, 'author_profile': 'https://Stackoverflow.com/users/77', 'pm_score': 3, 'selected': False, 'text': "<p>Generics avoid the performance hit of boxing and unboxing. Basically, look at ArrayList vs List&lt;T&gt;. Both do the same core things, but List&lt;T&gt; will be a lot faster because you don't have to box to/from object.</p>\n"}, {'answer_id': 77663, 'author': 'Steve Landey', 'author_id': 8061, 'author_profile': 'https://Stackoverflow.com/users/8061', 'pm_score': 1, 'selected': False, 'text': '<p>Generics let you use strong typing for objects and data structures that should be able to hold any object. It also eliminates tedious and expensive typecasts when retrieving objects from generic structures (boxing/unboxing).</p>\n\n<p>One example that uses both is a linked list. What good would a linked list class be if it could only use object Foo? To implement a linked list that can handle any kind of object, the linked list and the nodes in a hypothetical node inner class must be generic if you want the list to contain only one type of object.</p>\n'}, {'answer_id': 77682, 'author': 'gt124', 'author_id': 14093, 'author_profile': 'https://Stackoverflow.com/users/14093', 'pm_score': 1, 'selected': False, 'text': "<p>If your collection contains value types, they don't need to box/unbox to objects when inserted into the collection so your performance increases dramatically. Cool add-ons like resharper can generate more code for you, like foreach loops.</p>\n"}, {'answer_id': 77691, 'author': 'Tom Kidd', 'author_id': 2577, 'author_profile': 'https://Stackoverflow.com/users/2577', 'pm_score': 3, 'selected': False, 'text': '<p>I just like them because they give you a quick way to define a custom type (as I use them anyway).</p>\n\n<p>So for example instead of defining a structure consisting of a string and an integer, and then having to implement a whole set of objects and methods on how to access an array of those structures and so forth, you can just make a Dictionary</p>\n\n<pre><code>Dictionary&lt;int, string&gt; dictionary = new Dictionary&lt;int, string&gt;();\n</code></pre>\n\n<p>And the compiler/IDE does the rest of the heavy lifting. A Dictionary in particular lets you use the first type as a key (no repeated values).</p>\n'}, {'answer_id': 77709, 'author': 'ljs', 'author_id': 3394, 'author_profile': 'https://Stackoverflow.com/users/3394', 'pm_score': 8, 'selected': True, 'text': '<ul>\n<li>Allows you to write code/use library methods which are type-safe, i.e. a List&lt;string&gt; is guaranteed to be a list of strings.</li>\n<li>As a result of generics being used the compiler can perform compile-time checks on code for type safety, i.e. are you trying to put an int into that list of strings? Using an ArrayList would cause that to be a less transparent runtime error.</li>\n<li>Faster than using objects as it either avoids boxing/unboxing (where .net has to convert <a href="https://stackoverflow.com/questions/5057267/what-is-the-difference-between-a-reference-type-and-value-type-in-c">value types to reference types or vice-versa</a>) or casting from objects to the required reference type.</li>\n<li>Allows you to write code which is applicable to many types with the same underlying behaviour, i.e. a Dictionary&lt;string, int&gt; uses the same underlying code as a Dictionary&lt;DateTime, double&gt;; using generics, the framework team only had to write one piece of code to achieve both results with the aforementioned advantages too.</li>\n</ul>\n'}, {'answer_id': 77716, 'author': 'Kevin Pang', 'author_id': 1574, 'author_profile': 'https://Stackoverflow.com/users/1574', 'pm_score': 2, 'selected': False, 'text': '<p>The primary advantage, as Mitchel points out, is strong-typing without needing to define multiple classes.</p>\n\n<p>This way you can do stuff like:</p>\n\n<pre><code>List&lt;SomeCustomClass&gt; blah = new List&lt;SomeCustomClass&gt;();\nblah[0].SomeCustomFunction();\n</code></pre>\n\n<p>Without generics, you would have to cast blah[0] to the correct type to access its functions.</p>\n'}, {'answer_id': 77915, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>the jvm casts anyway... it implicitly creates code which treats the generic type as "Object" and creates casts to the desired instantiation.  Java generics are just syntactic sugar.</p>\n'}, {'answer_id': 77937, 'author': 'Chris Pietschmann', 'author_id': 7831, 'author_profile': 'https://Stackoverflow.com/users/7831', 'pm_score': 1, 'selected': False, 'text': '<p>Another advantage of using Generics (especially with Collections/Lists) is you get Compile Time Type Checking. This is really useful when using a Generic List instead of a List of Objects.</p>\n'}, {'answer_id': 77956, 'author': 'Vin', 'author_id': 1747, 'author_profile': 'https://Stackoverflow.com/users/1747', 'pm_score': 1, 'selected': False, 'text': '<p>Single most reason is they provide <strong>Type safety</strong></p>\n\n<pre><code>List&lt;Customer&gt; custCollection = new List&lt;Customer&gt;;\n</code></pre>\n\n<p>as opposed to,</p>\n\n<pre><code>object[] custCollection = new object[] { cust1, cust2 };\n</code></pre>\n\n<p>as a simple example.</p>\n'}, {'answer_id': 77970, 'author': 'Thomas Danecker', 'author_id': 9632, 'author_profile': 'https://Stackoverflow.com/users/9632', 'pm_score': 1, 'selected': False, 'text': "<p>In summary, generics allow you to specify more precisily what you intend to do (stronger typing).</p>\n\n<p>This has several benefits for you: </p>\n\n<ul>\n<li><p>Because the compiler knows more about what you want to do, it allows you to omit a lot of type-casting because it already knows that the type will be compatible.</p></li>\n<li><p>This also gets you earlier feedback about the correctnes of your program. Things that previously would have failed at runtime (e.g. because an object couldn't be casted in the desired type), now fail at compile-time and you can fix the mistake before your testing-department files a cryptical bug report.</p></li>\n<li><p>The compiler can do more optimizations, like avoiding boxing, etc.</p></li>\n</ul>\n"}, {'answer_id': 79081, 'author': 'SpongeJim', 'author_id': 13361, 'author_profile': 'https://Stackoverflow.com/users/13361', 'pm_score': 1, 'selected': False, 'text': '<p>A couple of things to add/expand on (speaking from the .NET point of view):</p>\n\n<p>Generic types allow you to create role-based classes and interfaces.  This has been said already in more basic terms, but I find you start to design your code with classes which are implemented in a type-agnostic way - which results in highly reusable code.</p>\n\n<p>Generic arguments on methods can do the same thing, but they also help apply the "Tell Don\'t Ask" principle to casting, i.e. "give me what I want, and if you can\'t, you tell me why".</p>\n'}, {'answer_id': 79281, 'author': 'etchasketch', 'author_id': 14640, 'author_profile': 'https://Stackoverflow.com/users/14640', 'pm_score': 2, 'selected': False, 'text': '<p>I know this is a C# question, but <a href="http://en.wikipedia.org/wiki/Generic_programming" rel="nofollow noreferrer">generics</a> are used in other languages too, and their use/goals are quite similar.</p>\n\n<p>Java collections use <a href="http://en.wikipedia.org/wiki/Generics_in_Java" rel="nofollow noreferrer">generics</a> since Java 1.5. So, a good place to use them is when you are creating your own collection-like object.</p>\n\n<p>An example I see almost everywhere is a Pair class, which holds two objects, but needs to deal with those objects in a generic way.</p>\n\n<pre><code>class Pair&lt;F, S&gt; {\n    public final F first;\n    public final S second;\n\n    public Pair(F f, S s)\n    { \n        first = f;\n        second = s;   \n    }\n}  \n</code></pre>\n\n<p>Whenever you use this Pair class you can specify which kind of objects you want it to deal with and any type cast problems will show up at compile time, rather than runtime.</p>\n\n<p>Generics can also have their bounds defined with the keywords \'super\' and \'extends\'. For example, if you want to deal with a generic type but you want to make sure it extends a class called Foo (which has a setTitle method):</p>\n\n<pre><code>public class FooManager &lt;F extends Foo&gt;{\n    public void setTitle(F foo, String title) {\n        foo.setTitle(title);\n    }\n}\n</code></pre>\n\n<p>While not very interesting on its own, it\'s useful to know that whenever you deal with a FooManager, you know that it will handle MyClass types, and that MyClass extends Foo.</p>\n'}, {'answer_id': 79339, 'author': 'Michael L Perry', 'author_id': 7668, 'author_profile': 'https://Stackoverflow.com/users/7668', 'pm_score': 0, 'selected': False, 'text': '<p>I once gave a talk on this topic. You can find my slides, code, and audio recording at <a href="http://www.adventuresinsoftware.com/generics/" rel="nofollow noreferrer">http://www.adventuresinsoftware.com/generics/</a>.</p>\n'}, {'answer_id': 79857, 'author': 'Dean Poulin', 'author_id': 5462, 'author_profile': 'https://Stackoverflow.com/users/5462', 'pm_score': 3, 'selected': False, 'text': '<p>The best benefit to Generics is code reuse.  Lets say that you have a lot of business objects, and you are going to write VERY similar code for each entity to perform the same actions.  (I.E Linq to SQL operations).</p>\n\n<p>With generics, you can create a class that will be able to operate given any of the types that inherit from a given base class or implement a given interface like so:</p>\n\n<pre><code>public interface IEntity\n{\n\n}\n\npublic class Employee : IEntity\n{\n    public string FirstName { get; set; }\n    public string LastName { get; set; }\n    public int EmployeeID { get; set; }\n}\n\npublic class Company : IEntity\n{\n    public string Name { get; set; }\n    public string TaxID { get; set }\n}\n\npublic class DataService&lt;ENTITY, DATACONTEXT&gt;\n    where ENTITY : class, IEntity, new()\n    where DATACONTEXT : DataContext, new()\n{\n\n    public void Create(List&lt;ENTITY&gt; entities)\n    {\n        using (DATACONTEXT db = new DATACONTEXT())\n        {\n            Table&lt;ENTITY&gt; table = db.GetTable&lt;ENTITY&gt;();\n\n            foreach (ENTITY entity in entities)\n                table.InsertOnSubmit (entity);\n\n            db.SubmitChanges();\n        }\n    }\n}\n\npublic class MyTest\n{\n    public void DoSomething()\n    {\n        var dataService = new DataService&lt;Employee, MyDataContext&gt;();\n        dataService.Create(new Employee { FirstName = "Bob", LastName = "Smith", EmployeeID = 5 });\n        var otherDataService = new DataService&lt;Company, MyDataContext&gt;();\n            otherDataService.Create(new Company { Name = "ACME", TaxID = "123-111-2233" });\n\n    }\n}\n</code></pre>\n\n<p>Notice the reuse of the same service given the different Types in the DoSomething method above.  Truly elegant!</p>\n\n<p>There\'s many other great reasons to use generics for your work, this is my favorite.</p>\n'}, {'answer_id': 953640, 'author': 'Steve B.', 'author_id': 19479, 'author_profile': 'https://Stackoverflow.com/users/19479', 'pm_score': 3, 'selected': False, 'text': '<ul>\n<li><p>Typed collections - even if you don\'t want to use them you\'re likely to have to deal with them from other libraries , other sources. </p></li>\n<li><p>Generic typing in class creation: </p>\n\n<p>public class Foo &lt; T> { \npublic T get()...</p></li>\n<li><p>Avoidance of casting - I\'ve always disliked things like </p>\n\n<p>new Comparator {\n   public int compareTo(Object o){\n     if (o instanceof classIcareAbout)...</p></li>\n</ul>\n\n<p>Where you\'re essentially checking for a condition that should only exist because the interface is expressed in terms of objects.</p>\n\n<p>My initial reaction to generics was similar to yours - "too messy, too complicated". My experience is that after using them for a bit you get used to them, and code without them feels less clearly specified, and just less comfortable. Aside from that, the rest of the java world uses them so you\'re going to have to get with the program eventually, right?</p>\n'}, {'answer_id': 953645, 'author': 'victor hugo', 'author_id': 70616, 'author_profile': 'https://Stackoverflow.com/users/70616', 'pm_score': 1, 'selected': False, 'text': '<p>I use them for example in a GenericDao implemented with SpringORM and Hibernate which look like this</p>\n\n<pre><code>public abstract class GenericDaoHibernateImpl&lt;T&gt; \n    extends HibernateDaoSupport {\n\n    private Class&lt;T&gt; type;\n\n    public GenericDaoHibernateImpl(Class&lt;T&gt; clazz) {\n        type = clazz;\n    }\n\n    public void update(T object) {\n        getHibernateTemplate().update(object);\n    }\n\n    @SuppressWarnings("unchecked")\n    public Integer count() {\n    return ((Integer) getHibernateTemplate().execute(\n        new HibernateCallback() {\n            public Object doInHibernate(Session session) {\n                    // Code in Hibernate for getting the count\n                }\n        }));\n    }\n  .\n  .\n  .\n}\n</code></pre>\n\n<p>By using generics my implementations of this DAOs force the developer to pass them just the entities they are designed for by just subclassing the GenericDao</p>\n\n<pre><code>public class UserDaoHibernateImpl extends GenericDaoHibernateImpl&lt;User&gt; {\n    public UserDaoHibernateImpl() {\n        super(User.class);     // This is for giving Hibernate a .class\n                               // work with, as generics disappear at runtime\n    }\n\n    // Entity specific methods here\n}\n</code></pre>\n\n<p><em>My little framework is more robust (have things like filtering, lazy-loading, searching). I just simplified here to give you an example</em></p>\n\n<p>I, like Steve and you, said at the beginning <em>"Too messy and complicated"</em> but now I see its advantages</p>\n'}, {'answer_id': 953646, 'author': 'Will Hartung', 'author_id': 13663, 'author_profile': 'https://Stackoverflow.com/users/13663', 'pm_score': 0, 'selected': False, 'text': '<p>Using generics for collections is just simple and clean. Even if you punt on it everywhere else, the gain from the collections is a win to me.</p>\n\n<pre><code>List&lt;Stuff&gt; stuffList = getStuff();\nfor(Stuff stuff : stuffList) {\n    stuff.do();\n}\n</code></pre>\n\n<p>vs </p>\n\n<pre><code>List stuffList = getStuff();\nIterator i = stuffList.iterator();\nwhile(i.hasNext()) {\n    Stuff stuff = (Stuff)i.next();\n    stuff.do();\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>List stuffList = getStuff();\nfor(int i = 0; i &lt; stuffList.size(); i++) {\n    Stuff stuff = (Stuff)stuffList.get(i);\n    stuff.do();\n}\n</code></pre>\n\n<p>That alone is worth the marginal "cost" of generics, and you don\'t have to be a generic Guru to use this and get value.</p>\n'}, {'answer_id': 953647, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 4, 'selected': False, 'text': '<p>If you were to search the Java bug database just before 1.5 was released, you\'d find seven times more bugs with <code>NullPointerException</code> than <code>ClassCastException</code>. So it doesn\'t seem that it is a great feature to find bugs, or at least bugs that persist after a little smoke testing.</p>\n\n<p>For me the huge advantage of generics is that they document <strong>in code</strong> important type information. If I didn\'t want that type information documented in code, then I\'d use a dynamically typed language, or at least a language with more implicit type inference.</p>\n\n<p>Keeping an object\'s collections to itself isn\'t a bad style (but then the common style is to effectively ignore encapsulation). It rather depends upon what you are doing. Passing collections to "algorithms" is slightly easier to check (at or before compile-time) with generics.</p>\n'}, {'answer_id': 953655, 'author': 'Peter Lange', 'author_id': 80164, 'author_profile': 'https://Stackoverflow.com/users/80164', 'pm_score': 3, 'selected': False, 'text': '<p>To give a good example. Imagine you have a class called Foo</p>\n\n<pre><code>public class Foo\n{\n   public string Bar() { return "Bar"; }\n}\n</code></pre>\n\n<p><strong>Example 1</strong>\nNow you want to have a collection of Foo objects. You have two options, LIst or ArrayList, both of which work in a similar manner.</p>\n\n<pre><code>Arraylist al = new ArrayList();\nList&lt;Foo&gt; fl = new List&lt;Foo&gt;();\n\n//code to add Foos\nal.Add(new Foo());\nf1.Add(new Foo());\n</code></pre>\n\n<p>In the above code, if I try to add a class of FireTruck instead of Foo, the ArrayList will add it, but the Generic List of Foo will cause an exception to be thrown.</p>\n\n<p><strong>Example two.</strong></p>\n\n<p>Now you have your two array lists and you want to call the Bar() function on each. Since hte ArrayList is filled with Objects, you have to cast them before you can call bar. But since the Generic List of Foo can only contain Foos, you can call Bar() directly on those.</p>\n\n<pre><code>foreach(object o in al)\n{\n    Foo f = (Foo)o;\n    f.Bar();\n}\n\nforeach(Foo f in fl)\n{\n   f.Bar();\n}\n</code></pre>\n'}, {'answer_id': 953665, 'author': 'Demi', 'author_id': 67985, 'author_profile': 'https://Stackoverflow.com/users/67985', 'pm_score': 2, 'selected': False, 'text': '<p>From the Sun Java documentation, in response to "why should i use generics?":</p>\n\n<p>"Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection... The code using generics is clearer and safer.... <strong>the compiler can verify at compile time that the type constraints are not violated at run time</strong> [emphasis mine]. Because the program compiles without warnings, we can state with certainty that it will not throw a ClassCastException at run time. The net effect of using generics, especially in large programs, is <strong>improved readability and robustness</strong>. [emphasis mine]"</p>\n'}, {'answer_id': 953683, 'author': 'James Schek', 'author_id': 17871, 'author_profile': 'https://Stackoverflow.com/users/17871', 'pm_score': 6, 'selected': False, 'text': "<p>I really hate to repeat myself. I hate typing the same thing more often than I have to. I don't like restating things multiple times with slight differences.</p>\n\n<p>Instead of creating:</p>\n\n<pre><code>class MyObjectList  {\n   MyObject get(int index) {...}\n}\nclass MyOtherObjectList  {\n   MyOtherObject get(int index) {...}\n}\nclass AnotherObjectList  {\n   AnotherObject get(int index) {...}\n}\n</code></pre>\n\n<p>I can build one reusable class... (in the case where you don't want to use the raw collection for some reason)</p>\n\n<pre><code>class MyList&lt;T&gt; {\n   T get(int index) { ... }\n}\n</code></pre>\n\n<p>I'm now 3x more efficient and I only have to maintain one copy. Why WOULDN'T you want to maintain less code?</p>\n\n<p>This is also true for non-collection classes such as a <code>Callable&lt;T&gt;</code> or a <code>Reference&lt;T&gt;</code> that has to interact with other classes. Do you really want to extend <code>Callable&lt;T&gt;</code> and  <code>Future&lt;T&gt;</code> and every other associated class to create type-safe versions?</p>\n\n<p>I don't.</p>\n"}, {'answer_id': 953699, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>Generics also give you the ability to create more reusable objects/methods while still providing type specific support. You also gain a lot of performance in some cases. I don't know the full spec on the Java Generics, but in .NET I can specify constraints on the Type parameter, like Implements a Interface, Constructor , and Derivation.</p>\n"}, {'answer_id': 953755, 'author': 'jigawot', 'author_id': 117724, 'author_profile': 'https://Stackoverflow.com/users/117724', 'pm_score': 2, 'selected': False, 'text': "<p>Don't forget that generics aren't just used by classes, they can also be used by methods.  For example, take the following snippet:</p>\n\n<pre><code>private &lt;T extends Throwable&gt; T logAndReturn(T t) {\n    logThrowable(t); // some logging method that takes a Throwable\n    return t;\n}\n</code></pre>\n\n<p>It is simple, but can be used very elegantly.  The nice thing is that the method returns whatever it was that it was given.  This helps out when you are handling exceptions that need to be re-thrown back to the caller:</p>\n\n<pre><code>    ...\n} catch (MyException e) {\n    throw logAndReturn(e);\n}\n</code></pre>\n\n<p>The point is that you don't lose the type by passing it through a method.  You can throw the correct type of exception instead of just a <code>Throwable</code>, which would be all you could do without generics.</p>\n\n<p>This is just a simple example of one use for generic methods.  There are quite a few other neat things you can do with generic methods.  The coolest, in my opinion, is type inferring with generics.  Take the following example (taken from Josh Bloch's Effective Java 2nd Edition):</p>\n\n<pre><code>...\nMap&lt;String, Integer&gt; myMap = createHashMap();\n...\npublic &lt;K, V&gt; Map&lt;K, V&gt; createHashMap() {\n    return new HashMap&lt;K, V&gt;();\n}\n</code></pre>\n\n<p>This doesn't do a lot, but it does cut down on some clutter when the generic types are long (or nested; i.e. <code>Map&lt;String, List&lt;String&gt;&gt;</code>).</p>\n"}, {'answer_id': 953756, 'author': 'coobird', 'author_id': 17172, 'author_profile': 'https://Stackoverflow.com/users/17172', 'pm_score': 5, 'selected': False, 'text': '<p><strong>Not needing to typecast is one of the biggest advantages of Java generics</strong>, as it will perform type checking at compile-time. This will reduce the possibility of <code>ClassCastException</code>s which can be thrown at runtime, and can lead to more robust code.</p>\n\n<p>But I suspect that you\'re fully aware of that.</p>\n\n<blockquote>\n  <p>Every time I look at Generics it gives\n  me a headache. I find the best part of\n  Java to be it\'s simplicity and minimal\n  syntax and generics are not simple and\n  add a significant amount of new\n  syntax.  </p>\n</blockquote>\n\n<p>At first, I didn\'t see the benefit of generics either. I started learning Java from the 1.4 syntax (even though Java 5 was out at the time) and when I encountered generics, I felt that it was more code to write, and I really didn\'t understand the benefits.</p>\n\n<p><strong>Modern IDEs make writing code with generics easier.</strong></p>\n\n<p>Most modern, decent IDEs are smart enough to assist with writing code with generics, especially with code completion.</p>\n\n<p>Here\'s an example of making an <code>Map&lt;String, Integer&gt;</code> with a <code>HashMap</code>. The code I would have to type in is:</p>\n\n<pre><code>Map&lt;String, Integer&gt; m = new HashMap&lt;String, Integer&gt;();\n</code></pre>\n\n<p>And indeed, that\'s a lot to type just to make a new <code>HashMap</code>. However, in reality, I only had to type this much before Eclipse knew what I needed:</p>\n\n<p><code>Map&lt;String, Integer&gt; m = new Ha</code> <kbd>Ctrl</kbd>+<kbd>Space</kbd></p>\n\n<p>True, I did need to select <code>HashMap</code> from a list of candidates, but basically the IDE knew what to add, including the generic types. With the right tools, using generics isn\'t too bad.</p>\n\n<p>In addition, since the types are known, when retrieving elements from the generic collection, the IDE will act as if that object is already an object of its declared type -- there is no need to casting for the IDE to know what the object\'s type is.</p>\n\n<p><strong>A key advantage of generics comes from the way it plays well with new Java 5 features.</strong> Here\'s an example of tossing integers in to a <code>Set</code> and calculating its total:</p>\n\n<pre><code>Set&lt;Integer&gt; set = new HashSet&lt;Integer&gt;();\nset.add(10);\nset.add(42);\n\nint total = 0;\nfor (int i : set) {\n  total += i;\n}\n</code></pre>\n\n<p>In that piece of code, there are three new Java 5 features present:</p>\n\n<ul>\n<li><a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html" rel="noreferrer">Generics</a></li>\n<li><a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html" rel="noreferrer">Autoboxing and unboxing</a></li>\n<li><a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html" rel="noreferrer">For-each loop</a></li>\n</ul>\n\n<p>First, generics and autoboxing of primitives allow the following lines:</p>\n\n<pre><code>set.add(10);\nset.add(42);\n</code></pre>\n\n<p>The integer <code>10</code> is autoboxed into an <code>Integer</code> with the value of <code>10</code>. (And same for <code>42</code>). Then that <code>Integer</code> is tossed into the <code>Set</code> which is known to hold <code>Integer</code>s. Trying to throw in a <code>String</code> would cause a compile error.</p>\n\n<p>Next, for for-each loop takes all three of those:</p>\n\n<pre><code>for (int i : set) {\n  total += i;\n}\n</code></pre>\n\n<p>First, the <code>Set</code> containing <code>Integer</code>s are used in a for-each loop. Each element is declared to be an <code>int</code> and that is allowed as the <code>Integer</code> is unboxed back to the primitive <code>int</code>. And the fact that this unboxing occurs is known because generics was used to specify that there were <code>Integer</code>s held in the <code>Set</code>.</p>\n\n<p>Generics can be the glue that brings together the new features introduced in Java 5, and it just makes coding simpler and safer. And most of the time IDEs are smart enough to help you with good suggestions, so generally, it won\'t a whole lot more typing.</p>\n\n<p>And frankly, as can be seen from the <code>Set</code> example, I feel that utilizing Java 5 features can make the code more concise and robust.</p>\n\n<p><strong>Edit - An example without generics</strong></p>\n\n<p>The following is an illustration of the above <code>Set</code> example without the use of generics. It is possible, but isn\'t exactly pleasant:</p>\n\n<pre><code>Set set = new HashSet();\nset.add(10);\nset.add(42);\n\nint total = 0;\nfor (Object o : set) {\n  total += (Integer)o;\n}\n</code></pre>\n\n<p><em>(Note: The above code will generate unchecked conversion warning at compile-time.)</em></p>\n\n<p>When using non-generics collections, the types that are entered into the collection is objects of type <code>Object</code>. Therefore, in this example, a <code>Object</code> is what is being <code>add</code>ed into the set.</p>\n\n<pre><code>set.add(10);\nset.add(42);\n</code></pre>\n\n<p>In the above lines, autoboxing is in play -- the primitive <code>int</code> value <code>10</code> and <code>42</code> are being autoboxed into <code>Integer</code> objects, which are being added to the <code>Set</code>. However, keep in mind, the <code>Integer</code> objects are being handled as <code>Object</code>s, as there are no type information to help the compiler know what type the <code>Set</code> should expect.</p>\n\n<pre><code>for (Object o : set) {\n</code></pre>\n\n<p>This is the part that is crucial. The reason the for-each loop works is because the <code>Set</code> implements the <a href="http://java.sun.com/javase/6/docs/api/java/lang/Iterable.html" rel="noreferrer"><code>Iterable</code></a> interface, which returns an <code>Iterator</code> with type information, if present. (<code>Iterator&lt;T&gt;</code>, that is.)</p>\n\n<p>However, since there is no type information, the <code>Set</code> will return an <code>Iterator</code> which will return the values in the <code>Set</code> as <code>Object</code>s, and that is why the element being retrieved in the for-each loop <em>must</em> be of type <code>Object</code>.</p>\n\n<p>Now that the <code>Object</code> is retrieved from the <code>Set</code>, it needs to be cast to an <code>Integer</code> manually to perform the addition:</p>\n\n<pre><code>  total += (Integer)o;\n</code></pre>\n\n<p>Here, a typecast is performed from an <code>Object</code> to an <code>Integer</code>. In this case, we know this will always work, but manual typecasting always makes me feel it is fragile code that could be damaged if a minor change is made else where. (I feel that every typecast is a <code>ClassCastException</code> waiting to happen, but I digress...)</p>\n\n<p>The <code>Integer</code> is now unboxed into an <code>int</code> and allowed to perform the addition into the <code>int</code> variable <code>total</code>.</p>\n\n<p>I hope I could illustrate that the new features of Java 5 is possible to use with non-generic code, but it just isn\'t as clean and straight-forward as writing code with generics. And, in my opinion, to take full advantage of the new features in Java 5, one should be looking into generics, if at the very least, allows for compile-time checks to prevent invalid typecasts to throw exceptions at runtime.</p>\n'}, {'answer_id': 953769, 'author': 'Bert F', 'author_id': 11296, 'author_profile': 'https://Stackoverflow.com/users/11296', 'pm_score': 2, 'selected': False, 'text': "<p>Haven't you ever written a method (or a class) where the key concept of the method/class wasn't tightly bound to a specific data type of the parameters/instance variables (think linked list, max/min functions, binary search, etc.).</p>\n\n<p>Haven't you ever wish you could reuse the algorthm/code without resorting to cut-n-paste reuse or compromising strong-typing (e.g. I want a <code>List</code> of Strings, not a <code>List</code> of things I <em>hope</em> are strings!)?</p>\n\n<p>That's why you should <strong><em>want</em></strong> to use generics (or something better).</p>\n"}, {'answer_id': 953781, 'author': 'Apocalisp', 'author_id': 3434, 'author_profile': 'https://Stackoverflow.com/users/3434', 'pm_score': 4, 'selected': False, 'text': '<p>Generics in Java facilitate <a href="http://en.wikipedia.org/wiki/Polymorphism_(computer_science)" rel="nofollow noreferrer">parametric polymorphism</a>. By means of type parameters, you can pass arguments to types. Just as a method like <code>String foo(String s)</code> models some behaviour, not just for a particular string, but for any string <code>s</code>, so a type like <code>List&lt;T&gt;</code> models some behaviour, not just for a specific type, but <em>for any type</em>. <code>List&lt;T&gt;</code> says that <em>for any type <code>T</code>, there\'s a type of <code>List</code> whose elements are <code>T</code>s</em>. So <code>List</code> is a actually a <em>type constructor</em>. It takes a type as an argument and constructs another type as a result.</p>\n\n<p>Here are a couple of examples of generic types I use every day. First, a very useful generic interface:</p>\n\n<pre><code>public interface F&lt;A, B&gt; {\n  public B f(A a);\n}\n</code></pre>\n\n<p>This interface says that <em>for some two types, <code>A</code> and <code>B</code>, there\'s a function (called <code>f</code>) that takes an <code>A</code> and returns a <code>B</code>.</em> When you implement this interface, <code>A</code> and <code>B</code> can be any types you want, as long as you provide a function <code>f</code> that takes the former and returns the latter. Here\'s an example implementation of the interface:</p>\n\n<pre><code>F&lt;Integer, String&gt; intToString = new F&lt;Integer, String&gt;() {\n  public String f(int i) {\n    return String.valueOf(i);\n  }\n}\n</code></pre>\n\n<p>Before generics, polymorphism was achieved by <em>subclassing</em> using the <code>extends</code> keyword. With generics, we can actually do away with subclassing and use parametric polymorphism instead. For example, consider a parameterised (generic) class used to calculate hash codes for any type. Instead of overriding Object.hashCode(), we would use a generic class like this:</p>\n\n<pre><code>public final class Hash&lt;A&gt; {\n  private final F&lt;A, Integer&gt; hashFunction;\n\n  public Hash(final F&lt;A, Integer&gt; f) {\n    this.hashFunction = f;\n  }\n\n  public int hash(A a) {\n    return hashFunction.f(a);\n  }\n}\n</code></pre>\n\n<p>This is much more flexible than using inheritance, because we can stay with the theme of using composition and parametric polymorphism without locking down brittle hierarchies.</p>\n\n<p>Java\'s generics are not perfect though. You can abstract over types, but you can\'t abstract over type constructors, for example. That is, you can say "for any type T", but you can\'t say "for any type T that takes a type parameter A".</p>\n\n<p><a href="http://apocalisp.wordpress.com/2008/10/23/heterogeneous-lists-and-the-limits-of-the-java-type-system/" rel="nofollow noreferrer">I wrote an article about these limits of Java generics, here.</a></p>\n\n<p>One huge win with generics is that they let you avoid subclassing. Subclassing tends to result in brittle class hierarchies that are awkward to extend, and classes that are difficult to understand individually without looking at the entire hierarchy.</p>\n\n<p>Wereas before generics you might have classes like <code>Widget</code> extended by <code>FooWidget</code>, <code>BarWidget</code>, and <code>BazWidget</code>, with generics you can have a single generic class <code>Widget&lt;A&gt;</code> that takes a <code>Foo</code>, <code>Bar</code> or <code>Baz</code> in its constructor to give you <code>Widget&lt;Foo&gt;</code>, <code>Widget&lt;Bar&gt;</code>, and <code>Widget&lt;Baz&gt;</code>.</p>\n'}, {'answer_id': 51103844, 'author': 'stdout', 'author_id': 1388943, 'author_profile': 'https://Stackoverflow.com/users/1388943', 'pm_score': 1, 'selected': False, 'text': '<p>Obvious benefits like "type safety" and "no casting" are already mentioned so maybe I can talk about some other "benefits" which I hope it helps.</p>\n\n<p>First of all, generics is a language-independent concept and , IMO, it might make more sense if you think about regular (runtime) polymorphism at the same time. </p>\n\n<p>For example, the polymorphism as we know from object oriented design has a runtime notion in where the caller object is figured out at runtime as program execution goes and the relevant method gets called accordingly depending on the runtime type. In generics, the idea is somewhat similar but everything happens at compile time. What does that mean and how you make use of it?</p>\n\n<p>(Let\'s stick with generic methods to keep it compact) It means that you can still have the same method on separate classes (like you did previously in polymorphic classes) but this time they\'re auto-generated by the compiler depend on the types set at compile time. You parametrise your methods on the type you give at compile time. So, instead of writing the methods from scratch <strong>for every single type</strong> you have as you do in runtime polymorphism (method overriding), you let compilers do the work during compilation. This has an obvious advantage since you don\'t need to infer all possible types that might be used in your system which makes it far more scalable without a code change.</p>\n\n<p>Classes work the pretty much same way. You parametrise the type and the code is generated by the compiler.</p>\n\n<p>Once you get the idea of "compile time", you can make use "bounded" types and restrict what can be passed as a parametrised type through classes/methods. So, you can control what to be passed through which is a powerful thing especially you\'ve a framework being consumed by other people.</p>\n\n<pre><code>public interface Foo&lt;T extends MyObject&gt; extends Hoo&lt;T&gt;{\n    ...\n}\n</code></pre>\n\n<p>No one can set sth other than MyObject now.</p>\n\n<p>Also, you can "enforce" type constraints on your method arguments which means you can make sure both your method arguments would depend on the same type.</p>\n\n<pre><code>public &lt;T extends MyObject&gt; foo(T t1, T t2){\n    ...\n}   \n</code></pre>\n\n<p>Hope all of this makes sense.</p>\n'}, {'answer_id': 64616245, 'author': 'Ash', 'author_id': 6497200, 'author_profile': 'https://Stackoverflow.com/users/6497200', 'pm_score': 0, 'selected': False, 'text': '<ol>\n<li><p>Enabling programmers to implement generic algorithms - By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type-safe and easier to read.</p>\n</li>\n<li><p>Stronger type checks at compile time - A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.</p>\n</li>\n<li><p>Elimination of casts.</p>\n</li>\n</ol>\n'}]
['https://Stackoverflow.com/questions/77632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13578/']