在Java中将boolean转换为int | Java Debug 笔记

本文正在参加「Java主题月 – Java Debug笔记活动」,详情查看 活动链接

问题: 在Java中将boolean转换为int

将Boolean转换为int的最常用方法是什么

回答一

int myInt = myBoolean ? 1 : 0;
复制代码

回答二

使用三源运算符是最简单,最有效,并且可读性最高的方法去完成你想要的。我鼓励你采用这种解法。

但是,我还是忍不住提出一个困难,低效,难读的替代方案

int boolToInt(Boolean b) {
    return b.compareTo(false);
}
复制代码

快给这么酷的答案点赞吧

编辑

顺便说一下,我经常看到一些从boolean到int的转换,而唯一的目的就是比较两个值(大多是为了实现compareTo方法)。Boolean#compareTo是那些特殊情况下的处理方法。

第二次编辑

Java7引入了一个新的工具方法Boolean#compare去直接处理元素类型

int boolToInt(boolean b) {
    return Boolean.compare(b, false);
}
复制代码

回答三

int val = b? 1 : 0;
复制代码

回答四

That depends on the situation. Often the most simple approach is the best because it is easy to understand:
视情况而定。通常来说最简单的方法就是最好的方法,因为容易理解

if (something) {
    otherThing = 1;
} else {
    otherThing = 0;
}
复制代码

或者

int otherThing = something ? 1 : 0;
复制代码

But sometimes it useful to use an Enum instead of a boolean flag. Let imagine there are synchronous and asynchronous processes:

但是有时候,使用枚举类型也能替代boolean。让我们来想象一下这里有一些同步和异步的进程

Process process = Process.SYNCHRONOUS;
System.out.println(process.getCode());
复制代码

Java里面,枚举可以拥有额外的属性和方法

public enum Process {

    SYNCHRONOUS (0),
    ASYNCHRONOUS (1);

    private int code;
    private Process (int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }
}

复制代码

文章翻译自Stack Overflow:stackoverflow.com/questions/3…

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享