<p>Java has generics and C++ provides a very strong programming model with <code>template</code>s.
So then, what is the difference between C++ and Java generics?</p>

[{'answer_id': 36356, 'author': 'Shog9', 'author_id': 811, 'author_profile': 'https://Stackoverflow.com/users/811', 'pm_score': 7, 'selected': False, 'text': "<p>C++ has templates. Java has generics, which look kinda sorta like C++ templates, but they're very, very different.</p>\n\n<p>Templates work, as the name implies, by providing the compiler with a (wait for it...) template that it can use to generate type-safe code by filling in the template parameters. </p>\n\n<p>Generics, as I understand them, work the other way around: the type parameters are used by the compiler to verify that the code using them is type-safe, but the resulting code is generated without types at all. </p>\n\n<p>Think of C++ templates as a <em>really good</em> macro system, and Java generics as a tool for automatically generating typecasts.</p>\n\n<p>&nbsp;</p>\n"}, {'answer_id': 36364, 'author': 'Alexandru Nedelcu', 'author_id': 3280, 'author_profile': 'https://Stackoverflow.com/users/3280', 'pm_score': 8, 'selected': True, 'text': '<p>There is a big difference between them. In C++ you don\'t have to specify a class or an interface for the generic type. That\'s why you can create truly generic functions and classes, with the caveat of a looser typing.</p>\n<pre class="lang-cpp prettyprint-override"><code>template &lt;typename T&gt; T sum(T a, T b) { return a + b; }\n</code></pre>\n<p>The method above adds two objects of the same type, and can be used for any type T that has the &quot;+&quot; operator available.</p>\n<p>In Java you have to specify a type if you want to call methods on the objects passed, something like:</p>\n<pre class="lang-java prettyprint-override"><code>&lt;T extends Something&gt; T sum(T a, T b) { return a.add ( b ); }\n</code></pre>\n<p>In C++ generic functions/classes can only be defined in headers, since the compiler generates different functions for different types (that it\'s invoked with). So the compilation is slower. In Java the compilation doesn\'t have a major penalty, but Java uses a technique called &quot;erasure&quot; where the generic type is erased at runtime, so at runtime Java is actually calling ...</p>\n<pre class="lang-java prettyprint-override"><code>Something sum(Something a, Something b) { return a.add ( b ); }\n</code></pre>\n<p>Nevertheless, Java\'s generics help with type-safety.</p>\n'}, {'answer_id': 41510, 'author': 'Ferruccio', 'author_id': 4086, 'author_profile': 'https://Stackoverflow.com/users/4086', 'pm_score': 2, 'selected': False, 'text': '<p>Java (and C#) generics seem to be a simple run-time type substitution mechanism.\n<br>\nC++ templates are a compile-time construct which give you a way to modify the language to suit your needs. They are  actually a purely-functional language that the compiler executes during a compile.</p>\n'}, {'answer_id': 41930, 'author': 'KeithB', 'author_id': 2298, 'author_profile': 'https://Stackoverflow.com/users/2298', 'pm_score': 2, 'selected': False, 'text': '<p>Another advantage of C++ templates is specialization.  </p>\n\n<pre class="lang-cpp prettyprint-override"><code>template &lt;typename T&gt; T sum(T a, T b) { return a + b; }\ntemplate &lt;typename T&gt; T sum(T* a, T* b) { return (*a) + (*b); }\nSpecial sum(const Special&amp; a, const Special&amp; b) { return a.plus(b); }\n</code></pre>\n\n<p>Now, if you call sum with pointers, the second method will be called, if you call sum with non-pointer objects the first method will be called, and if you call <code>sum</code> with <code>Special</code> objects, the third will be called.  I don\'t think that this is possible with Java.</p>\n'}, {'answer_id': 41973, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 1, 'selected': False, 'text': "<p>@Keith:</p>\n\n<p>That code is actually wrong and apart from the smaller glitches (<code>template</code> omitted, specialization syntax looks differently), partial specialization <em>doesn't</em> work on function templates, only on class templates. The code would however work without partial template specialization, instead using plain old overloading:</p>\n\n<pre><code>template &lt;typename T&gt; T sum(T a, T b) { return a + b; }\ntemplate &lt;typename T&gt; T sum(T* a, T* b) { return (*a) + (*b); }\n</code></pre>\n"}, {'answer_id': 498321, 'author': 'OscarRyz', 'author_id': 20654, 'author_profile': 'https://Stackoverflow.com/users/20654', 'pm_score': 3, 'selected': False, 'text': '<p>Basically, AFAIK, C++ templates create a copy of the code for each type, while Java generics use exactly the same code.</p>\n\n<p>Yes, you <em>can say</em> that C++ template is equivalent to Java generic <strong>concept</strong> ( although more properly would be to say Java generics are equivalent to C++ in concept ) </p>\n\n<blockquote>\n  <p><em>If you are familiar with C++\'s template mechanism, you might think that generics are similar, but the similarity is superficial. Generics do not generate a new class for each specialization, nor do they permit “template metaprogramming.”</em></p>\n</blockquote>\n\n<p>from: <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html" rel="noreferrer">Java Generics</a></p>\n'}, {'answer_id': 498329, 'author': 'cletus', 'author_id': 18393, 'author_profile': 'https://Stackoverflow.com/users/18393', 'pm_score': 7, 'selected': False, 'text': '<p>Java Generics are <strong>massively</strong> different to C++ templates.</p>\n<p>Basically in C++ templates are basically a glorified preprocessor/macro set (<strong>Note:</strong> since some people seem unable to comprehend an analogy, I\'m not saying template processing is a macro). In Java they are basically syntactic sugar to minimize boilerplate casting of Objects. Here is a pretty decent <a href="http://web.archive.org/web/20090323084529/http://www.mindview.net/WebLog/log-0061" rel="noreferrer">introduction to C++ templates vs Java generics</a>.</p>\n<p>To elaborate on this point: when you use a C++ template, you\'re basically creating another copy of the code, just as if you used a <code>#define</code> macro. This allows you to do things like have <code>int</code> parameters in template definitions that determine sizes of arrays and such.</p>\n<p>Java doesn\'t work like that. In Java all objects extent from <a href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html" rel="noreferrer">java.lang.Object</a> so, pre-Generics, you\'d write code like this:</p>\n<pre class="lang-java prettyprint-override"><code>public class PhoneNumbers {\n    private Map phoneNumbers = new HashMap();\n    \n    public String getPhoneNumber(String name) {\n      return (String) phoneNumbers.get(name);\n    }\n}\n</code></pre>\n<p>because all the Java collection types used Object as their base type so you could put anything in them. Java 5 rolls around and adds generics so you can do things like:</p>\n<pre class="lang-java prettyprint-override"><code>public class PhoneNumbers {\n    private Map&lt;String, String&gt; phoneNumbers = new HashMap&lt;String, String&gt;();\n    \n    public String getPhoneNumber(String name) {\n        return phoneNumbers.get(name);\n    }\n}\n</code></pre>\n<p>And that\'s all Java Generics are: wrappers for casting objects. That\'s because Java Generics aren\'t refined. They use type erasure. This decision was made because Java Generics came along so late in the piece that they didn\'t want to break backward compatibility (a <code>Map&lt;String, String&gt;</code> is usable whenever a <code>Map</code> is called for). Compare this to .Net/C# where type erasure isn\'t used, which leads to all sorts of differences (e.g. you can use primitive types and <code>IEnumerable</code> and <code>IEnumerable&lt;T&gt;</code> bear no relation to each other).</p>\n<p>And a class using generics compiled with a Java 5+ compiler is usable on JDK 1.4 (assuming it doesn\'t use any other features or classes that require Java 5+).</p>\n<p>That\'s why Java Generics are called <a href="http://en.wikipedia.org/wiki/Syntactic_sugar" rel="noreferrer">syntactic sugar</a>.</p>\n<p>But this decision on how to do generics has profound effects so much so that the (superb) <a href="http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html" rel="noreferrer">Java Generics FAQ</a> has sprung up to answer the many, many questions people have about Java Generics.</p>\n<p>C++ templates have a number of features that Java Generics don\'t:</p>\n<ul>\n<li><p>Use of primitive type arguments.</p>\n<p>For example:</p>\n<pre><code>template&lt;class T, int i&gt;\nclass Matrix {\n    int T[i][i];\n    ...\n}\n</code></pre>\n<p>Java does not allow the use of primitive type arguments in generics.</p>\n</li>\n<li><p>Use of <a href="http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/default_args_for_templ_params.htm" rel="noreferrer">default type arguments</a>, which is one feature I miss in Java but there are backwards compatibility reasons for this;</p>\n</li>\n<li><p>Java allows bounding of arguments.</p>\n<p>For example:</p>\n<pre class="lang-java prettyprint-override"><code>public class ObservableList&lt;T extends List&gt; {\n    ...\n}\n</code></pre>\n</li>\n</ul>\n<p>It really does need to be stressed that template invocations with different arguments really are different types. They don\'t even share static members. In Java this is not the case.</p>\n<p>Aside from the differences with generics, for completeness, here is a <a href="http://www.javacoffeebreak.com/articles/thinkinginjava/comparingc++andjava.html" rel="noreferrer">basic comparison of C++ and Java</a> (and <a href="http://triton.towson.edu/%7Emzimand/os/Lect2-java-tutorial.html" rel="noreferrer">another one</a>).</p>\n<p>And I can also suggest <a href="https://rads.stackoverflow.com/amzn/click/com/0131872486" rel="noreferrer" rel="nofollow noreferrer">Thinking in Java</a>. As a C++ programmer a lot of the concepts like objects will be second nature already but there are subtle differences so it can be worthwhile to have an introductory text even if you skim parts.</p>\n<p>A lot of what you\'ll learn when learning Java is all the libraries (both standard--what comes in the JDK--and nonstandard, which includes commonly used things like Spring). Java syntax is more verbose than C++ syntax and doesn\'t have a lot of C++ features (e.g. operator overloading, multiple inheritance, the destructor mechanism, etc) but that doesn\'t strictly make it a subset of C++ either.</p>\n'}, {'answer_id': 499272, 'author': 'Julien Chastang', 'author_id': 32174, 'author_profile': 'https://Stackoverflow.com/users/32174', 'pm_score': 4, 'selected': False, 'text': '<p>There is a great explanation of this topic in <a href="http://oreilly.com/catalog/9780596527754/" rel="nofollow noreferrer">Java Generics and Collections</a>\n By Maurice Naftalin, Philip Wadler. I highly recommend this book. To quote:</p>\n\n<blockquote>\n  <p>Generics in Java resemble templates in\n  C++. ... The syntax is deliberately\n  similar and the semantics are\n  deliberately different. ...\n  Semantically, Java generics are\n  defined by erasure, where as C++\n  templates are defined by expansion.</p>\n</blockquote>\n\n<p>Please read the full explanation <a href="http://books.google.com/books?id=3keGb40PWJsC&amp;dq=java+generics+and+collections&amp;printsec=frontcover&amp;source=bn&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=5&amp;ct=result#PPA6,M1" rel="nofollow noreferrer">here</a>.</p>\n\n<p><a href="https://i.stack.imgur.com/AwwDu.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AwwDu.gif" alt="alt text"></a><br>\n<sub>(source: <a href="http://oreilly.com/catalog/covers/0596527756_cat.gif" rel="nofollow noreferrer">oreilly.com</a>)</sub>  </p>\n'}, {'answer_id': 499289, 'author': 'KeithB', 'author_id': 2298, 'author_profile': 'https://Stackoverflow.com/users/2298', 'pm_score': 4, 'selected': False, 'text': "<p>Another feature that C++ templates have that Java generics don't is specialization.  That allows you to have a different implementation for specific types.  So you can, for example, have a highly optimized version for an <em>int</em>, while still having a generic  version for the rest of the types.  Or you can have different versions for pointer and non-pointer types.  This comes in handy if you want to operate on the dereferenced object when handed a pointer.</p>\n"}, {'answer_id': 18420523, 'author': 'MigMit', 'author_id': 1722752, 'author_profile': 'https://Stackoverflow.com/users/1722752', 'pm_score': 0, 'selected': False, 'text': '<p>Templates are nothing but a macro system. Syntax sugar. They are fully expanded before actual compilation (or, at least, compilers behave as if it were the case).</p>\n\n<p>Example:</p>\n\n<p>Let\'s say we want two functions. One function takes two sequences (list, arrays, vectors, whatever goes) of numbers, and returns their inner product. Another function takes a length, generates two sequences of that length, passes them to the first function, and returns it\'s result. The catch is that we might make a mistake in the second function, so that these two functions aren\'t really of the same length. We need the compiler to warn us in this case. Not when the program is running, but when it\'s compiling.</p>\n\n<p>In Java you can do something like this:</p>\n\n<pre><code>import java.io.*;\ninterface ScalarProduct&lt;A&gt; {\n    public Integer scalarProduct(A second);\n}\nclass Nil implements ScalarProduct&lt;Nil&gt;{\n    Nil(){}\n    public Integer scalarProduct(Nil second) {\n        return 0;\n    }\n}\nclass Cons&lt;A implements ScalarProduct&lt;A&gt;&gt; implements ScalarProduct&lt;Cons&lt;A&gt;&gt;{\n    public Integer value;\n    public A tail;\n    Cons(Integer _value, A _tail) {\n        value = _value;\n        tail = _tail;\n    }\n    public Integer scalarProduct(Cons&lt;A&gt; second){\n        return value * second.value + tail.scalarProduct(second.tail);\n    }\n}\nclass _Test{\n    public static Integer main(Integer n){\n        return _main(n, 0, new Nil(), new Nil());\n    }\n    public static &lt;A implements ScalarProduct&lt;A&gt;&gt; \n      Integer _main(Integer n, Integer i, A first, A second){\n        if (n == 0) {\n            return first.scalarProduct(second);\n        } else {\n            return _main(n-1, i+1, \n                         new Cons&lt;A&gt;(2*i+1,first), new Cons&lt;A&gt;(i*i, second));\n            //the following line won\'t compile, it produces an error:\n            //return _main(n-1, i+1, first, new Cons&lt;A&gt;(i*i, second));\n        }\n    }\n}\npublic class Test{\n    public static void main(String [] args){\n        System.out.print("Enter a number: ");\n        try {\n            BufferedReader is = \n              new BufferedReader(new InputStreamReader(System.in));\n            String line = is.readLine();\n            Integer val = Integer.parseInt(line);\n            System.out.println(_Test.main(val));\n        } catch (NumberFormatException ex) {\n            System.err.println("Not a valid number");\n        } catch (IOException e) {\n            System.err.println("Unexpected IO ERROR");\n        }\n    }\n}\n</code></pre>\n\n<p>In C# you can write almost the same thing. Try to rewrite it in C++, and it won\'t compile, complaining about infinite expansion of templates.</p>\n'}, {'answer_id': 35109742, 'author': 'user207421', 'author_id': 207421, 'author_profile': 'https://Stackoverflow.com/users/207421', 'pm_score': 2, 'selected': False, 'text': '<p>I will sum it up in a single sentence: templates create new types, generics restricts existing types.</p>\n'}, {'answer_id': 51124855, 'author': 'Jswq', 'author_id': 5579519, 'author_profile': 'https://Stackoverflow.com/users/5579519', 'pm_score': 2, 'selected': False, 'text': '<p>The answer below is from the book <strong>Cracking The Coding Interview</strong> Solutions to Chapter 13, which I think is very good.</p>\n\n<p>The implementation of Java generics is rooted in an idea of"type erasure:\'This technique eliminates the parameterized types when source code is translated to the Java Virtual Machine (JVM) bytecode. For example, suppose you have the Java code below:</p>\n\n<pre><code>Vector&lt;String&gt; vector = new Vector&lt;String&gt;();\nvector.add(new String("hello"));\nString str = vector.get(0);\n</code></pre>\n\n<p>During compilation, this code is re-written into:</p>\n\n<pre><code>Vector vector = new Vector();\nvector.add(new String("hello"));\nString str = (String) vector.get(0);\n</code></pre>\n\n<p>The use of Java generics didn\'t really change much about our capabilities; it just made things a bit prettier. For this reason, Java generics are sometimes called"syntactic sugar:\'.</p>\n\n<p>This is quite different from C++. In C++, templates are essentially a glorified macro set, with the compiler creating a new copy of the template code for each type. Proof of this is in the fact that an instance of MyClass will not share a static variable withMyClass. Tow instances of MyClass, however, will share a static variable.</p>\n\n<pre><code>/*** MyClass.h ***/\n template&lt;class T&gt; class MyClass {\n public:\n static int val;\n MyClass(int v) { val v;}\n };\n /*** MyClass.cpp ***/\n template&lt;typename T&gt;\n int MyClass&lt;T&gt;::bar;\n\n template class MyClass&lt;Foo&gt;;\n template class MyClass&lt;Bar&gt;;\n\n /*** main.cpp ***/\n MyClass&lt;Foo&gt; * fool\n MyClass&lt;Foo&gt; * foo2\n MyClass&lt;Bar&gt; * barl\n MyClass&lt;Bar&gt; * bar2\n\n new MyClass&lt;Foo&gt;(10);\n new MyClass&lt;Foo&gt;(15);\n new MyClass&lt;Bar&gt;(20);\n new MyClass&lt;Bar&gt;(35);\n int fl fool-&gt;val; // will equal 15\n int f2 foo2-&gt;val; // will equal 15\n int bl barl-&gt;val; // will equal 35\n int b2 bar2-&gt;val; // will equal 35\n</code></pre>\n\n<p>In Java, static variables are shared across instances of MyClass, regardless of the diﬀerent type parameters.</p>\n\n<p>Java generics and C ++ templates have a number of other differences. These include:</p>\n\n<ul>\n<li>C++ templates can use primitive types, like int. Java cannot and must\ninstead use Integer.</li>\n<li>In Java, you can restrict the template\'s type parameters to be of a\ncertain type. For instance, you might use generics to implement a\nCardDeck and specify that the type parameter must extend from\nCardGame.</li>\n<li>In C++, the type parameter can be instantiated, whereas Java does not\nsupport this.</li>\n<li>In Java, the type parameter (i.e., the Foo in MyClass) cannot be\nused for static methods and variables, since these would be shared between MyClass and MyClass. In C++, these classes are diﬀerent, so the type parameter can be used for static methods and variables.</li>\n<li>In Java, all instances of MyClass, regardless of their type parameters, are the same type. The type parameters are erased at runtime. In C++, instances with different type parameters are diﬀerent types.</li>\n</ul>\n'}, {'answer_id': 62862886, 'author': 'Piyush-Ask Any Difference', 'author_id': 1029089, 'author_profile': 'https://Stackoverflow.com/users/1029089', 'pm_score': 0, 'selected': False, 'text': '<p>I would like to quote <a href="https://askanydifference.com" rel="nofollow noreferrer">askanydifference</a> here:</p>\n<p>The main difference between C++ and Java lies in their dependency on the platform. While, C++ is platform dependent language, Java is platform independent language.</p>\n<p>The above statement is the reason why C++ is able to provide true generic types. While Java does have strict checking and hence they don\'t allow using generics the way C++ allows it.</p>\n'}]
['https://Stackoverflow.com/questions/36347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1556/']