java 设置变量

标签 java variables colors

我在使用下面的代码时遇到了一些问题。我的问题是变量 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/

相关文章:

java - 使用生成的端点和 gae 实现 Multi-Tenancy

java - JFileChooser 和 "Details View"

java - 使用 TwitterStream 对推文进行采样是否正常,如 Twitter4J 代码示例中所示,我主要得到的只是问号作为用户名和状态?

javascript - 如何从 .php 脚本增加 javascript 变量

ios - 颜色计算 : increase alpha but maintain the same color appearance over a white background

colors - 透明 ARGB 十六进制值

java - 使用正则表达式的模式匹配用数字替换

javascript - 我可以在多行 php 变量中插入 php 和 html 吗?

variables - 第一天 lua - 被 for 循环弄糊涂了

Python OpenCV : Why does fillPoly() only draw grey polygons, 无论其颜色参数如何?