views:

2078

answers:

9

Java has the generic keyword and C++ provides a very strong programming model with templates. So then, what is the difference between C++ and Java generics?

+11  A: 

C++ has templates. Java has generics, which look kinda sorta like C++ templates, but they're very, very different.

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.

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 are type-safe, but the resulting code is generated without types at all.

Think of C++ templates as a really good macro system, and Java generics as a tool for automatically generating typecasts.

Shog9
This is a pretty good, concise explanation. One tweak I'd be tempted to make is that Java generics is a tool for automatically generating typecasts *that are guaranteed to be safe* (with some conditions). In some ways they're related to C++'s `const`. An object in C++ won't be modified through a `const` pointer unless the `const`-ness is casted away. Likewise, the implicit casts created by generic types in Java are guaranteed to be "safe" unless the type parameters are manually casted away somewhere in the code.
Laurence Gonsalves
+2  A: 

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.

<typename T> T sum(T a, T b) { return a + b; }

The method above adds two objects of the same type, and can be used for any type T that has the "+" operator available.

In Java you have to specify a type if you want to call methods on the objects passed, something like:

<T extends Something> T sum(T a, T b) { return a.add ( b ); }

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 "erasure" where the generic type is erased at runtime, so at runtime Java is actually calling ...

Something sum(Something a, Something b) { return a.add ( b ); }

So generic programming in Java is not really useful, it's only a little syntactic sugar to help with the new foreach construct.

Alexandru Nedelcu
-1, WTF? @ *"So generic programming in Java is not really useful, it's only a little syntactic sugar to help with the new foreach construct."*
missingfaktor
Yeah, pretty good answer until that last sentence.
Laurence Gonsalves
A: 

Java (and C#) generics seem to be a simple run-time type substitution mechanism.
C++ 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.

Ferruccio
A: 

Another advantage of C++ templates is specilization.

<typename T> T sum(T a, T b) { return a + b; }
<typename T*> T sum(T* a, T* b) { return (*a) + (*b); }
Special sum(const Special& a, const Special& b) { return a.plus(b); }

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 sum() with Special objects, the third will be called. I don't think that this is possible with Java.

KeithB
A: 

@Keith:

That code is actually wrong and apart from the smaller glitches (template omitted, specialization syntax looks differently), partial specialization doesn't work on function templates, only on class templates. The code would however work without partial template specialization, instead using plain old overloading:

template <typename T> T sum(T a, T b) { return a + b; }
template <typename T> T sum(T* a, T* b) { return (*a) + (*b); }
Konrad Rudolph
Why is this an answer and not a comment?
Laurence Gonsalves
@Laurence: for once, because it was posted long before comments were implemented on Stack Overflow. For another, because it’s not only a comment – it’s also an answer to the question: something like the above code isn’t possible in Java.
Konrad Rudolph
A: 

Basically, AFAIK, C++ templates create a copy of the code for each type, while Java generics use exactly the same code.

Yes, you can say that C++ template is equivalent to Java generic concept ( although more properly would be to say Java generics are equivalent to C++ in concept )

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.”

from: Java Generics

OscarRyz
+21  A: 

Java Generics are massively different to C++ templates.

Basically in C++ templates are basically a glorified preprocessor/macro set (Note: 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 introduction to C++ templates vs Java generics.

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 #define macro. This allows you to do things like have int parameters in template definitions that determine sizes of arrays and such.

Java doesn't work like that. In Java all objects extent from java.lang.Object so, pre-Generics, you'd write code like this:

public class PhoneNumbers {
  private Map phoneNumbers = new HashMap();

  public String getPhoneNumber(String name) {
    return (String)phoneNumbers.get(name);
  }

  ...
}

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:

public class PhoneNumbers {
  private Map<String, String> phoneNumbers = new HashMap<String, String>();

  public String getPhoneNumber(String name) {
    return phoneNumbers.get(name);
  }

  ...
}

And that's all Java Generics are: wrappers for casting objects. That's because Java Generics aren't reified. 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 Map<String, String> is usable whenever a Map is called for). Compare this to .Net/C# where type erasure isn't used, which leads to all sorts of differences (eg you can use primitive types and IEnumerable and IEnumerable<T> bear no relation to each other).

And a class using generics compiled with a Java 5+ compiler is usable no JDK 1.4 (assuming it doesn't use any ohter features or classes that require Java 5+).

That's why Java Generics are called syntactic sugar.

But this decision on how to do generics has profound effects so much so that the (superb) Java Generics FAQ has sprung up to answer the many, many questions people have about Java Generics.

C++ templates have a number of features that Java Generics don't:

  • Use of primitive type arguments.

For example:

template<class T, int i>
class Matrix {
  int T[i][i];
  ...
}
  • Use of default type arguments, which is one feature I miss in Java but there are backwards compatibility reasons for this;
  • C++ allows the use of primitive type arguments, Java doesn't; and
  • Java allows bounding of arguments.

For example:

public class ObservableList<T extends List> {
  ...
}

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.

Aside from the differences with generics, for completeness, here is a basic comparison of C++ and Java (and another one).

And I can also suggest Thinking in Java. 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.

A lot of what you'll learn when laerning 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 (eg operator overloading, mutliple inheritance, the destructor mechanism, etc) but that doesn't strictly make it a subset of C++ either.

cletus
They are completely different in implmentation, but equivalent ( or at least similar ) in concept, that is what tina asked.
OscarRyz
They are not equivalent in concept. The best example being the curiously recurring template pattern. The second-best being policy-oriented design. The third-best being the fact that C++ allows integral numbers to be passed in the angle brackets (myArray<5>).
Max Lybbert
No, they're not equivalent in concept. There is some overlap in the concept, but not much. Both allow you to create List<T>, but that's about as far as it goes. C++ templates go a lot further.
jalf
Important to note that the type erasure issue means more than just backwards compatability for `Map map = new HashMap<String, String>`. It means you can deploy new code on an old JVM and it will run due to the similarities in bytecode.
Yuval A
C++ templates have nothing to do with the preprocessors or macros. They never expand to text.
Nemanja Trifunovic
You'll note I said "basically a glorified preprocessor/macro". It was an analogy because each template declaration will create more code (as opposed to Java/C#).
cletus
Maybe it will and maybe won't create more code - modern compilers are pretty good at removing duplicated code; but the point is that template instantiation is nothing like macro text expansion - thinking in those terms can lead to nasty bugs.
Nemanja Trifunovic
I disagree. If you odn't think in those terms you may make the mistake of thinking static instance members are shared between template types, which they aren't. Template code isn't much above copy-and-paste (and I don't mean this in a bad way) hence the macro comparison.
cletus
Template code is *very* different than copy-and-paste. If you think in terms of macro expansion, sooner or later you'll be hit by subtle bugs such as this one: http://womble.decadentplace.org.uk/c++/template-faq.html#type-syntax-error
Nemanja Trifunovic
@cletus: broken link.
Lazer
`IEnumerable<T>` inherits from `IEnumerable`, so I wouldn't say that they bear no relation to each other.
svick
+4  A: 
Julien Chastang
+2  A: 

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 int, 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.

KeithB
+1 template specialization is incredibly important for compile-time metaprogramming - this difference in itself makes java generics that much less potent
Faisal Vali