gpt4 book ai didi

java - 为什么我会收到不可转换的类型错误?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:59:19 25 4
gpt4 key购买 nike

如果我使用这个类:

public class BooleanTest {
public static void main(String args[]) {
final Object[] objarray = new Object[2];
try {
objarray[0] = "Hello World!";
objarray[1] = false;
} catch (NullPointerException e) {
}
boolean bool = (boolean) objarray[1];
}
}

它工作正常,我可以毫无问题地分配 boolean。为什么在向我的用户询问密码时我不能做同样的事情?

final Object result[] = new Object[2];
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,0));
JLabel label = new JLabel();

label.setHorizontalAlignment(SwingConstants.LEADING);
JTextField input = new JTextField();

input.setHorizontalAlignment(SwingConstants.CENTER);
JCheckBox checkbox = new JCheckBox("Pair with this device");
checkbox.setHorizontalAlignment(SwingConstants.LEADING);
panel.add(label);
panel.add(input);
panel.add(checkbox);
if (wrong) {
label.setText("Wrong password. Please enter the password from the other device:");
} else {
label.setText("Please enter the password from the other device:");
}
int response = JOptionPane.showConfirmDialog(SendGUI.this, panel, "Enter password", JOptionPane.OK_CANCEL_OPTION);
if (response == JOptionPane.OK_OPTION) {
result[0] = input.getText();
result[1] = (boolean)checkbox.isSelected();
} else {
result[0] = null;
result[1] = false;
}
}
});
} catch (InterruptedException e) {
} catch (InvocationTargetException e) {
}
boolean pair = (boolean)result[1]; //inconvertible type, expected boolean found Object

据我所知,我在这两种情况下都做了同样的事情,但第一个示例编译正常,而第二个示例则没有。

最佳答案

您正在使用不同的编译器选项。你一定是。这两段代码都在 Java 7 规则下编译;两者都不会在 Java 6 规则下编译。例如,以您的第一代码(您说的为您编译的代码)为例:

c:\Users\Jon\Test>javac -source 1.7 BooleanTest.java

(No console output, i.e. no errors)

c:\Users\Jon\Test>javac -source 1.6 BooleanTest.java
warning: [options] bootstrap class path not set in conjunction with -source 1.6
BooleanTest.java:10: error: inconvertible types
boolean bool = (boolean) objarray[1];
^
required: boolean
found: Object
1 error
1 warning

编辑:我相信更改在 JLS(转换转换)的第 5.5 节中。

Java 7 version包括:

Casting contexts allow the use of one of:

  • ...
  • a narrowing reference conversion (§5.1.6) optionally followed by either an unboxing conversion (§5.1.8) or an unchecked conversion (§5.1.9)

JLS 3rd edition (基本上是 Java 5 和 6)包括:

Casting contexts allow the use of one of:

  • ...
  • a narrowing reference conversion (§5.1.6) optionally followed by an unchecked conversion

请注意此处缺少“拆箱转换”。

关于java - 为什么我会收到不可转换的类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15769308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com