为什么可以使用Java中使用仿制药作为整数施放对象?
我找到了通过通用类型将浮子添加到整数阵列中的方法。我很好奇为什么Java不会在运行时错误中抓住这一点?我尝试查找文档以获取有关此信息的任何信息,但我没有任何运气。
例如,假设我有两个阵列列表,一个包含整数,一个包含浮子,例如:
ArrayList<Integer> listInt = new ArrayList<>();
ArrayList<Float> listFlt = new ArrayList<>();
listInt.add(6);
listInt.add(71);
listFlt.add(4.92f);
listFlt.add(20.5f);
使用generics,我可以通过这样的方法将floats从listflt复制到listint中:
public static <T extends Number, S extends Number> void copy(ArrayList<T> src, ArrayList<S> dest) {
for (int i = 0; i < src.size(); i++) {
Object x = src.get(i);
dest.set(i, (S)x);
}
}
现在使用:
ClassName.<Float, Integer>copy(listFlt, listInt);
现在,当我打印ListInt时,它显示:
4.92
20.5
当涉及仿制药时,如何将对象作为整数施放? ListInt如何存储浮标?谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
中
使用仿制药,我可以通过这样的方法将 (您不应该忽略!)。
它允许,但是由于擦除类型,JVM是否允许在运行时检查。
这是 arrayList 中的情况(在这种情况下:您将
float
对象添加到应该用于的列表中包含整数
对象)。当您仅打印列表时,没有问题,因为在这种情况下,Java只需要在列表元素上调用
toString()
,并且所有对象都存在该方法。但是,当您尝试将
整数
从列表中删除时,您将获得classcastexception
:这是Java规则组合的不幸结果,这部分是它们的方式是因为向后兼容,以及Java与仿制药(使用类型擦除)一起使用的方式。
要记住的角度:不要忽略“不受控制的演员”警告;他们暗示您的代码可能会发生堆污染。
Note that inside this method, you are casting to the type parameter
S
:This will cause an unchecked cast warning when you compile it (which you should not ignore!).
It's allowed, but because of type erasure, the JVM will not be able to check at runtime if the cast is allowed.
This is an example of heap pollution: because of the rules of the Java language and type erasure, you get into a situation where you can add objects into an
ArrayList
that are of the wrong type (in this case: you are addingFloat
objects to a list that is supposed to containInteger
objects).When you just print the list, there is no problem, because in that case Java only needs to call
toString()
on the elements of the list, and that method exists for all objects.But when you try to get an
Integer
out of the list, you will get aClassCastException
:It's an unfortunate consequence of a combination of the rules of Java, which are partly the way they are because of backward compatibility, and the way that Java works with generics (with type erasure).
Point to remember: Do not ignore "unchecked cast" warnings; they are a hint that there is possible heap pollution going on in your code.