Why are generics called generics?

后端 未结 9 842
野性不改
野性不改 2021-02-04 00:48

At the risk of becoming the village idiot, can someone explain to me why generics are called generics? I understand their usage and benefits, but if the definition of generic i

相关标签:
9条回答
  • 2021-02-04 01:41

    Okay, take this with a grain of salt, because I'm totally guessing, but I wonder whether it might be a bastardization of "Generative Types".

    Conceptually, when you specialize a List into a List< String >, it generates a new type. At least, that's the way it works in C++ templates and in C# generics.

    In Java, since the parameterizations are discarded by the compiler using type erasure, it actually doesn't generate a new specialized type, so who knows?

    I suppose you could say that Java implements a genericized version of generative types :)


    ON EDIT:

    Here's another point of view...

    The type List< String > is not what they're talking about when they refer to a "generic" type. I think the terminology is actually referring to the List< T > type, which is how the type exists in its generic form. List< String > is a specialization of the generic List< T >.

    0 讨论(0)
  • 2021-02-04 01:45

    Because you are creating "Generic" code that will be capable of operating on any type (within constraints you specify) in the same way...

    a good example you are familiar with is the Add operator is just about any language... it can "Add" integers, floats, doubles, decimals, binarys, hexadecimals, regardless of whether they are signed, unsogned, how many bits they are, etc...

    0 讨论(0)
  • 2021-02-04 01:52

    A class which takes objects is NOT generic, it is very specifically taking a type which is itself a generic type. A generic class, on the other hand, can be used with any specific type.

    0 讨论(0)
提交回复
热议问题