缺少泛型在编程中意味着什么?

sym*_*ony 0 generics programming-languages

有人说,在对这个答案的评论中

我一般都要推荐Apache Commons,因为如果你发现有用的东西,它实际上是50:50.那里肯定有很多宝石,但也有很多不好的和过时的东西,例如此时令人担忧的缺乏Generics是不可原谅的 - 即使引入它们的Java 5已经达到了EOL!

在这种情况下,"缺乏泛型"是什么意思?你能用外行的话解释一下吗?

R. *_*des 6

提到的"缺乏泛型"是指API暴露非泛型方法和类,即处理Object并通常强制用户使用强制转换并失去某些类型安全性的方法.通用API具有类型参数并且可以处理这些类型的对象,而无需强制转换和维护编译时类型安全性.比较ArrayList使用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
Run Code Online (Sandbox Code Playgroud)