Java 泛型的乐趣
有人知道如何使用泛型编写下面的代码并避免编译器警告吗? (@SuppressWarnings("unchecked") 被认为是作弊)。
并且,也许通过泛型检查“左”的类型与“右”的类型相同?
public void assertLessOrEqual(Comparable left, Comparable right) {
if (left == null || right == null || (left.compareTo(right) > 0)) {
String msg = "["+left+"] is not less than ["+right+"]";
throw new RuntimeException("assertLessOrEqual: " + msg);
}
}
Anybody knows how to write the piece of code below using generics AND avoiding compiler warnings ? (@SuppressWarnings("unchecked") is considered cheating).
And, maybe, checking via generics that the type of "left" is the same as the type of "right" ?
public void assertLessOrEqual(Comparable left, Comparable right) {
if (left == null || right == null || (left.compareTo(right) > 0)) {
String msg = "["+left+"] is not less than ["+right+"]";
throw new RuntimeException("assertLessOrEqual: " + msg);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这也适用于 Comparable 类型的子类:
This works with subclasses of Comparable types too:
怎么样:
它可能会变得更通用一点,但也只能让它变得更复杂:)
How about this:
It could probably be made a little bit more general, but only by making it more complicated as well :)
您无法通过泛型检查运行时“左”的类型是否与“右”的类型相同。 Java泛型是通过类型擦除实现的,因此有关泛型类型参数的信息在运行时会丢失。
You cannot via generics check if the type of 'left' is the same as the type of 'right' at runtime. Java generics is implemented via type erasure, so that the information about the generic type parameters is lost at runtime.