Programing

Java에서 부울 변수를 전환하는 가장 확실한 방법은 무엇입니까?

lottogame 2020. 5. 8. 08:11
반응형

Java에서 부울 변수를 전환하는 가장 확실한 방법은 무엇입니까?


간단한 if-else보다 Java에서 부울을 무효화하는 더 좋은 방법이 있습니까?

if (theBoolean) {
    theBoolean = false;
} else {
    theBoolean = true;
}

theBoolean = !theBoolean;

theBoolean ^= true;

변수가 4 글자보다 길면 더 적은 키 입력


몇 가지가 있습니다

"명백한"방법 (대부분의 사람들)

theBoolean = !theBoolean;

"가장 짧은"방법 (대부분의 경우)

theBoolean ^= true;

"가장 시각적 인"방법 (가장 확실치 않음)

theBoolean = theBoolean ? false : true;

추가 : 메소드 호출에서 전환 및 사용

theMethod( theBoolean ^= true );

대입 연산자는 항상 할당 된 값을 반환하므로 비트 연산자를 통해 값을 토글 한 다음 메서드 호출에 사용할 새로 할당 된 값을 반환합니다.


부울 NULL 값을 사용하고 false로 간주하면 다음을 시도하십시오.

static public boolean toggle(Boolean aBoolean) {
    if (aBoolean == null) return true;
    else return !aBoolean;
}

부울 NULL 값을 전달하지 않으면 다음을 시도하십시오.

static public boolean toggle(boolean aBoolean) {
   return !aBoolean;
}

이들은입니다 깨끗한 그들이 메서드 서명의 의도를 보여 때문에에 비해 쉽게 읽을 수 있습니다 ! 연산자로 쉽게 디버깅 할 수 있습니다.

용법

boolean bTrue = true
boolean bFalse = false
boolean bNull = null

toggle(bTrue) // == false
toggle(bFalse) // == true
toggle(bNull) // == true

물론 Groovy 또는 확장 방법을 허용하는 언어를 사용하는 경우 확장을 등록하고 간단하게 수행 할 수 있습니다.

Boolean b = false
b = b.toggle() // == true

특히 전문적인 작업을 수행하지 않는 경우 항상 Util 클래스를 사용할 수 있습니다. 예를 들어, 클래스 프로젝트의 util 클래스입니다.

public class Util {


public Util() {}
public boolean flip(boolean bool) { return !bool; }
public void sop(String str) { System.out.println(str); }

}

그런 다음 Util 객체를 만들고 Util u = new Util();반환 할 무언가를 갖습니다.System.out.println( u.flip(bool) );

똑같은 것을 계속 사용하려면 메소드를 사용하십시오. 특히 프로젝트 전체에 걸쳐 있다면 Util 클래스를 만드십시오. 그러나 업계 표준이 무엇인지 모르겠습니다. (경험이 풍부한 프로그래머는 자유롭게 고쳐주세요)


This answer came up when searching for "java invert boolean function". The example below will prevent certain static analysis tools from failing builds due to branching logic. This is useful if you need to invert a boolean and haven't built out comprehensive unit tests ;)

Boolean.valueOf(aBool).equals(false)

or alternatively:

Boolean.FALSE.equals(aBool)

or

Boolean.FALSE::equals

Before:

boolean result = isresult();
if (result) {
    result = false;
} else {
    result = true;
}

After:

boolean result = isresult();
result ^= true;

참고URL : https://stackoverflow.com/questions/224311/cleanest-way-to-toggle-a-boolean-variable-in-java

반응형