开发者

What does lacking of generics mean in programming?

开发者 https://www.devze.com 2022-12-23 10:17 出处:网络
In the comments to this answer someone says Ihave to downvote recommending Apache Commons in general since it\'s really a 50:50 chance on if you find something useful or not. There\'s certainly a lo

In the comments to this answer someone says

I have to downvote recommending Apache Commons in general since it's really a 50:50 chance on if you find something useful or not. There's certainly a lot of gems in there but there's also lots of bad and outdated stuff too, for example the worrying lack of Generics at this point is just inexcusable - even Java 5 which introduced the开发者_运维百科m has reached EOL!

In this context, what does "lack of Generics" mean? Can you explain it in layman's terms?


The "lack of generics" mentioned refers to the fact that the API exposes non-generic methods and classes, i.e. methods that work on Object and typically force the user to use casts and lose some type-safety. Generic APIs have type parameters and work on objects of those types, without the need for casts and maintaining compile-time type-safety. Compare using ArrayList to using ArrayList<T>:

// Non-generic (before Java 5)
ArrayList l = /*...*/;
Foo x = (Foo) l.get(42);
l.add(new Bar()); // Compiler is fine with this

// Generic (from Java 5 onwards)
ArrayList<Foo> l = /*...*/;
Foo x = l.get(42);
l.add(new Bar()); // Compiler complains that you can't add Bar to a list of Foo


Without generics you won't be able to "generalize" your code, that is, you won't be able to use the same code with different object types.


Generics allow you to create methods and classes that work with different types of object. Without using generics, you would have to cast to and from the object type, and lose some type-safety.

Get more info on what generics are here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号