gpt4 book ai didi

java - 为什么 getRGB() 方法是这样写的?是否有其他方法来编写 getRGB() 方法?

转载 作者:行者123 更新时间:2023-12-01 21:48:54 26 4
gpt4 key购买 nike

我是 Java 新手。我从Java教程Oracle中看到了下面的代码。我正在努力理解此代码片段的用途:

    public synchronized int getRGB() {
return ((red << 16) | (green << 8) | blue);
}

我理解按位运算符的工作原理,但我很难理解为什么 getRGB() 方法是这样编写的。是否有其他方法来编写 getRGB() 方法?

public class SynchronizedRGB {

// Values must be between 0 and 255.
private int red;
private int green;
private int blue;
private String name;

private void check(int red,
int green,
int blue) {
if (red < 0 || red > 255
|| green < 0 || green > 255
|| blue < 0 || blue > 255) {
throw new IllegalArgumentException();
}
}

public SynchronizedRGB(int red,
int green,
int blue,
String name) {
check(red, green, blue);
this.red = red;
this.green = green;
this.blue = blue;
this.name = name;
}

public void set(int red,
int green,
int blue,
String name) {
check(red, green, blue);
synchronized (this) {
this.red = red;
this.green = green;
this.blue = blue;
this.name = name;
}
}

public synchronized int getRGB() {
return ((red << 16) | (green << 8) | blue);
}

public synchronized String getName() {
return name;
}

public synchronized void invert() {
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
name = "Inverse of " + name;
}

public static void main(String[] args) {
SynchronizedRGB color = new SynchronizedRGB(0, 0, 0, "Pitch black");
System.out.println(color.getRGB());
}
}

最佳答案

左移运算符<< x相当于乘以2^x,所以可以写成

return ((red * 65536 ) + (green *256) + blue);

关于java - 为什么 getRGB() 方法是这样写的?是否有其他方法来编写 getRGB() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35494889/

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