java - 可以将类型转换变量转换为空值吗?

标签 java swing

我目前正在阅读 Poornachandra Sarang 的 Java Programming 并且对 JListgetSelectedValue() 函数在 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/

相关文章:

java - 如何在 JTextArea 中打印符号、非字母数字字符

java - 多次执行jar文件并分析输出

java - 迭代所有具有特定注释的类

数据库架构中的 Java 类

java - CardLayout 显示下一个面板 - java Swing

java - 元素不会出现在具有 GridLayout 或 FlowLayout 的面板中,但具有 setBounds 时它们会出现在面板中

java - 如何在java中解码base64

java - 抽象方法的目的是什么?

swing 未捕获的异常处理程序

java - 多线程在 GUI JFrame 中显示 java 控制台日志