可以将突变变量转换为空值



我目前正在阅读Poornachandra Sarang的Java编程,并且对Java Swing中使用JListgetSelectedValue()函数有疑问。

我注意到不仅source.getSelectedValue() != null(其中sourceJList(检查一次,而且在被转换为字符串后再次检查,如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);
            }
        }
     }
}
诸如

(字符串(之类的强制转换是否可以将变量更改为空值?

不。 绝对不行。 (String) someObject给你null的唯一方法是someObject的值是否已经null .

然而。。。

可以想象,以下内容可以将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;
        // ...
    }

但是,这不一定能解决其他潜在的争用条件。

鉴于此,诸如(字符串(之类的强制转换是否可以将变量突变为空值?

不,一旦你走到了这一步,你就可以放心,source.getSelectedValue()永远不会为空。

此外,第二个空检查是多余的,可以删除。

希望能:)回答您的问题

最新更新