我目前正在阅读 Poornachandra Sarang 的 Java Programming 并且对 JList
的 getSelectedValue()
函数在 Java 中的用法有疑问 Swing 。
我注意到不仅 source.getSelectedValue() != null
(其中 source
是一个 JList
)检查了一次,而且在转换为字符串后再次检查,如 str != null
所示。
鉴于此,(String)
之类的转换是否有可能将变量变为 null
值?
public void actionPerformed(ActionEvent evt) {
if (evt.getSource().equals(addButton)) {
if (source.getSelectedValue() != null) {
String str = (String) source.getSelectedValue();
if(str != null) {
destModel.addElement(str);
dest.setSelectedIndex(0);
sourceModel.removeElement(str);
source.setSelectedIndex(0);
}
}
}
}
最佳答案
Is it possible for a cast such as (String) to mutate a variable into the null value?
没有。绝对不。 (String) someObject
给你 null
的唯一方法是 someObject
的值已经 空
。
然而……
可以想象,以下可以将null
赋值给str
。
if (source.getSelectedValue() != null) {
String str = (String) source.getSelectedValue();
在多线程上下文中(在实践中 Swing UI 通常是多线程的!),另一个线程可能会在代码正在执行时改变 source
所以对 getSelectedValue()
的第一次和第二次调用返回不同 值。这是否是一个实际问题(以及可能的解决方案)将取决于大局。
部分解决方案(即针对该特定竞争条件)将重写该部分代码,如下所示:
Object selected = source.getSelectedValue();
if (selected != null) {
String str = (String) selected;
// ...
}
但是,这并不一定能解决其他潜在的竞争条件。
关于java - 可以将类型转换变量转换为空值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55859848/