我在使用下面的代码时遇到了一些问题。我的问题是变量 BGCLRFORPNLS 的值与变量 c 的值不同。但它应该可以工作,因为这个变量是一个引用。
public static Color BGCLRFORPNLS = Color.BLACK;
private static void Initialze() {
List<Color> colors = new ArrayList<Color>();
colors.add(BGCLRFORPNLS);
Color c = colors.get(0);
JOptionPane.showMessageDialog(null, "hashcode of c: "+ c.hashCode());
JOptionPane.showMessageDialog(null, "hashcode of BGCLRFORPNLS: "+ BGCLRFORPNLS.hashCode());
c = Color.red;
JOptionPane.showMessageDialog(null, "color of c: "+ c.toString());
JOptionPane.showMessageDialog(null, "color of BGCLRFORPNLS: "+ BGCLRFORPNLS.toString());
}
最佳答案
不,它不应该工作,因为 c
是对 Color
对象的引用,当您更改它时,您不会更改对该对象的任何其他引用并且您不会更改对象的值,而只会更改特定的引用。
statement | BGCLRFORPNLS | colors[0] | c
---------------------------------------------------------------------------------
BGCLRFORPNLS = Color.BLACK; | Color.BLACK | ---- | ------
colors.add(BGCLRFORPNLS); | Color.BLACK | Color.BLACK | ------
Color c = colors.get(0); | Color.BLACK | Color.BLACK | Color.BLACK
c = Color.red; | Color.BLACK | Color.BLACK | Color.red
关于java 设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9664134/