-2

Today I was reading a lot of articles complaining about Java Generics or C++ Templates. Now, my question is: How can someone implement a collection data structure like Stack without using them?

  • 1
    Just open the source of a JDK prior to generics and read it? – Ordous Aug 4 '16 at 18:45
  • 5
    Quite easily - for example by either dropping type safety or the flexibility to accept multiple types. – Hulk Aug 4 '16 at 18:50
  • 2
    That said, Java Generics and C++ Templates are two very different things. Don't be fooled by their deceptively similar <> syntax. – Hulk Aug 4 '16 at 18:53
  • 1
    @mahdix oracle.com/technetwork/java/javase/archive-139210.html Generics were added in Java 1.5, while Stack was added in 1.0. So any version from 1.0 to 1.4 should do the trick. The general idea is that they did not guarantee type safety at compile time. – Ordous Aug 4 '16 at 18:56
  • 1
    Yes, but they achieve this in very different ways and provide a quite different set of features with different compile-time and run-time characteristics. – Hulk Aug 4 '16 at 19:04
3

As the OP correctly stated in a comment, both of these language constructs were added to their respective langugae to enable developers to write type-independent code and still provide compile-time type-safety.

Before they were added, this was not possible in these languages. You could either flexible or (compile-time) typesafe code, but not both. Collection types typically valued code-reuse more than compile-time type-checking and could therefore contain anything, leaving it to their users to perform runtime checks (e.g. in the form of casts).

In languages that do not provide such a feature (e.g. C), this is still the case - just have a look at their libraries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.