Why are generics called generics?

2020-05-22 07:49发布

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 is "general" and generic collections are type safe, then why isn't this a misnomer?

For example, an ArrayList can hold anything that's an object:

ArrayList myObjects = new ArrayList();
myObjects.Add("one");
myObjects.Add(1);

while a generic collection of type string can only hold strings:

var myStrings = new List<string>();
myStrings.Add("one");
myStrings.Add("1");

I'm just not clear on why it's called "generic". If the answer is "...which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code." from here, then I suppose that makes sense. Perhaps I'm having this mental lapse because I only began programming after Java introduced generics, so I don't recall a time before them. But still...

Any help is appreciated.

9条回答
Rolldiameter
2楼-- · 2020-05-22 08:16

"Generic" is talking about the implementation. You write a single "Generic" list implementation that works with any type, instead of having to write specific implementations for each type you want to use.

查看更多
\"骚年 ilove
3楼-- · 2020-05-22 08:18

If they called it "type parameter(s)" people would confuse it with parameters of type Type.

Also, ArrayList isn't "generic". It ONLY works with types of object. If you ask it for something, it will give you an object reference. That's a very specific behavior.

查看更多
可以哭但决不认输i
4楼-- · 2020-05-22 08:27

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

查看更多
登录 后发表回答