1

我看过一段Java代码enum

public enum Classname {
    UIViewAutoresizingNone(0), 
    UIViewAutoresizingFlexibleLeftMargin(1 << 0), 
    UIViewAutoresizingFlexibleWidth(1 << 1), 
    UIViewAutoresizingFlexibleRightMargin(1 << 2), 
    UIViewAutoresizingFlexibleTopMargin(1 << 3), 
    UIViewAutoresizingFlexibleHeight(1 << 4), 
    UIViewAutoresizingFlexibleBottomMargin(1 << 5);

    private int value;

    // constructor
    private Classname(int v) {
        this.value = v;
    }

    public int value() {
        return value;
    }
}

System.out.println(Classname.UIViewAutoresizingFlexibleBottomMargin.value);

输出:32

我想结果是 2 的 5 次方。

一般来说,如果是

i << j 

express(i << j) 是什么意思?i 和 j 如何影响结果?有人可以指点我的教程吗?

4

3 回答 3

3

<<运算符是Java中的左位移位运算符。例如i为 1,位为00000001。左移位 ( j) 是 5:00100000即 32。左移位是将整数值乘以 2 的幂的一种快速方法。

此外,我应该提到int这里使用的数据类型是 32 位,而不是 8 位(为简单起见,我在上面显示了最低的 8 位)。如果您不小心,也可以将位“移开”并丢失它们。

于 2013-04-24T00:00:24.093 回答
0

<< is the left shift operator. If you consider an integer as a binary string, it shifts the string one to the left and cuts off the leftmost bit (i.e. 0b000101 becomes 0b01010). In terms of basic arithmetic, excluding overflow, this acts as a multiplication by two. Thus, 1<<5 is 0b100000, or 2^5, or 32.

In the expression i<<j, i is the base number being operated on, where j is the number of shifts occurring. When i is one, as in your example, 1<<n creates a binary string where the n+1th bit is set and no other bits are set. This is useful because you can then add these strings together and check each individual bit to see if that particular option is on.

于 2013-04-24T00:04:20.540 回答
0

Java 枚举是类。它们可以有实例变量,尽管使它们可写是一种非常糟糕的形式。构造函数

private Classname(int v) {
    this.value = v;
}

意味着Classname必须使用 int 值构造实例。该声明UIViewAutoresizingNone(0)将 的值设置UIViewAutoresizingNone为 0,可能是为了使用外部代码。

然而,这是在 Java 中工作的一种有点愚蠢的方式。在 C 语言中,可以编写一个类似的枚举:

typedef enum {
    UIViewAutoresizingNone                 = 0, 
    UIViewAutoresizingFlexibleLeftMargin   = 1 << 0, 
    UIViewAutoresizingFlexibleWidth        = 1 << 1, 
    UIViewAutoresizingFlexibleRightMargin  = 1 << 2, 
    UIViewAutoresizingFlexibleTopMargin    = 1 << 3, 
    UIViewAutoresizingFlexibleHeight       = 1 << 4, 
    UIViewAutoresizingFlexibleBottomMargin = 1 << 5
} Classname;

Java 和 C 之间的区别在于,在 C 中,枚举是真正ints的核心。鉴于上述声明,这样写是完全合法的,

Classname windowOptions = UIViewAutoresizingFlexibleLeftMargin |
                          UIViewAutoresizingFlexibleRightMargin;

这会将 windowOptions 设置为1 | 4 == 5,并且外部系统将能够使用&操作员来挑选选项。

在 Java 中,你不能这样做。相反,您将使用EnumSet<Classname>

EnumSet<Classname> windowOptions =
    EnumSet.of(Classname.UIViewAutoresizingFlexibleLeftMargin,
               Classname.UIViewAutoresizingFlexibleRightMargin);

窗口系统将用于Set.contains确定已设置哪些选项。要做在 C 世界中所做的事情,必须有人写:

int bitMask = 0;
for(Classname option: windowOptions) {
    bitMask |= option.getValue();
}

坦率地说,这是一团糟。

于 2013-04-24T00:19:12.730 回答