Programming

Java에서 부울 대 부울

procodes 2020. 5. 26. 21:16
반응형

Java에서 부울 대 부울


Java Integer와 관련 int하여 토론이 있습니다 . 전자의 기본값 null은 후자에 있습니다 0. 어떻 Booleanboolean?

내 응용 프로그램의 변수는 0/ 1값을 가질 수 있습니다 . 나는 boolean/ 를 사용 Boolean하고 싶습니다 int. 대신 Boolean/ boolean사용할 수 있습니까 ?


Boolean / boolean대신 사용할 수 있습니다 .

첫 번째는 Object이고 두 번째는 기본 유형입니다.

  • 처음에는 더 많은 메소드를 얻을 수 있습니다.

  • 두 번째는 메모리 비용을 고려하여 저렴합니다 . 두 번째는 더 많은 메모리를 절약하므로 계속하십시오.

이제 길을 선택하십시오.


Boolean 부울 프리미티브 유형을 래핑 합니다. JDK 5 이상에서 Oracle (또는 Oracle이 구입하기 전에 Sun)은 autoboxing / unboxing을 도입 했습니다.

boolean result = Boolean.TRUE;

또는

Boolean result = true; 

본질적으로 컴파일러는

Boolean result = Boolean.valueOf(true);

따라서 대답은 그렇습니다.


지금까지 그들이 "자신"에 / 특정 언어 프로그래밍 대신의 장면 뒤에 더 큰 그림을 돌보는에 초점 인공 용어에 집중할 때부터 (제공 답변을 연장하는 비트입니다 프로그래밍 언어를 만드는 , 즉 일을 일반적으로, 형식 안전성 대 메모리 고려 사항이 차이를 만듭니다) :

int는 부울이 아닙니다

치다

    boolean bar = true;      
    System.out.printf("Bar is %b\n", bar);
    System.out.printf("Bar is %d\n", (bar)?1:0);
    int baz = 1;       
    System.out.printf("Baz is %d\n", baz);
    System.out.printf("Baz is %b\n", baz);

출력

    Bar is true
    Bar is 1
    Baz is 1
    Baz is true

3 번째 줄의 Java 코드 (bar)?1:0bar ( boolean )를 암시 적으로 int 로 변환 (캐스팅) 할 수 없음을 보여 줍니다 . JVM 뒤에 구현의 세부 사항을 설명하지 않고 메모리 크기와 같은 낮은 수준의 고려 사항에서 유형 안전보다 값을 선호해야한다고 지적했습니다. 특히 유형 안전이 검사가 다음과 같은 형식으로 수행되는 부울 유형과 같이 진정으로 / 완전히 사용되지 않는 경우

\ in {0,1} 값이면 부울 유형으로 캐스트되고, 그렇지 않으면 예외가 발생합니다.

모두 {0,1} <{-2 ^ 31, .., 2 ^ 31 -1}입니다. 과잉 인 것 같아요? 형식 안전성은 기본 형식의 암시 적 캐스팅이 아니라 사용자 정의 형식에서 매우 중요합니다 (마지막은 첫 번째 형식에도 포함됨).

바이트는 유형 또는 비트가 아닙니다

메모리에서 {0,1} 범위의 변수는 특별히주의하지 않는 한 (예 : 메모리에 멋지게 포장 됨-8 "부울") 최소 바이트 또는 단어 (레지스터 크기에 따라 xbits)를 차지합니다. 비트를 1 바이트로-앞뒤로).

추가 값 패킹 (예 : 비트 시프트 또는 산술 사용)보다 유형 안전 (특정 유형의 상자에 값을 넣거나 감는 것과 같이)을 선호함으로써 더 많은 메모리를 얻는 것보다 적은 코드를 작성하는 것을 효과적으로 선택합니다. 반면에 항상 부울보다 가치가없는 모든 변환을 용이하게하는 사용자 정의 사용자 유형을 정의 할 수 있습니다.

키워드와 유형

마지막으로 귀하의 질문은 키워드유형을 비교하는 것 입니다. 유형 (다른 키워드 클래스를 사용하는 일반 복합 사용자 정의 가능 클래스 ) 또는 다른 말로 키워드 ( " 기본 "으로 표시)를 사용하거나 선호함으로써 성능을 얻는 이유 또는 방법을 설명하는 것이 중요하다고 생각합니다.

boolean foo = true;

vs.

Boolean foo = true;

첫 번째 "thing"(유형)은 이유없이 확장 (하위 분류) 할 수 없습니다. 프리미티브랩핑 클래스 의 Java 용어를 효과적으로 인라인 값 (LITERAL 또는 상수 대체로 유추 할 수있는 경우 또는 컴파일러가 값을 래핑하는 경우 대체 할 수있는 경우 컴파일러가 직접 대체하는 상수) 으로 간단히 변환 할 수 있습니다 .

사소한 이유로 인해 최적화가 이루어집니다.

"런타임 캐스팅 작업이 줄어 듭니다.

그렇기 때문에 실제 형식 추론이 완료되면 필요한 경우 모든 형식 정보로 클래스를 래핑하는 경우 (또는 여전히) 변환 (또는 변환) 할 수 있습니다.

그래서, 차이 부울부울 에 정확하게 컴파일런타임 (조금 멀리 가고 있지만 거의 instanceof를getClass () ).

마지막으로 오토 박싱은 프리미티브보다 느립니다.

Note the fact that Java can do autoboxing is just a "syntactic sugar". It does not speed up anything, just allows you to write less code. That's it. Casting and wrapping into type information container is still performed. For performance reasons choose arithmetics which will always skip extra housekeeping of creating class instances with type information to implement type safety. Lack of type safety is the price you pay to gain performance. For code with boolean-valued expressions type safety (when you write less and hence implicit code) would be critical e.g. for if-then-else flow controls.


You can use the Boolean constants - Boolean.TRUE and Boolean.FALSE instead of 0 and 1. You can create your variable as of type boolean if primitive is what you are after. This way you won't have to create new Boolean objects.


Basically boolean represent a primitive data type where Boolean represent a reference data type. this story is started when Java want to become purely object oriented it's provided wrapper class concept to over come to use of primitive data type.

boolean b1;
Boolean b2;

b1 and b2 are not same.


One observation: (though this can be thought of side effect)

boolean being a primitive can either say yes or no.

Boolean is an object (it can refer to either yes or no or 'don't know' i.e. null)


You can use Boolean / boolean. Simplicity is the way to go. If you do not need specific api (Collections, Streams, etc.) and you are not foreseeing that you will need them - use primitive version of it (boolean).

  1. With primitives you guarantee that you will not pass null values.
    You will not fall in traps like this. The code below throws NullPointerException (from: Booleans, conditional operators and autoboxing):

    public static void main(String[] args) throws Exception { Boolean b = true ? returnsNull() : false; // NPE on this line. System.out.println(b); } public static Boolean returnsNull() { return null; }

  2. Use Boolean when you need an object, eg:

    • Stream of Booleans,
    • Optional
    • Collections of Booleans

참고URL : https://stackoverflow.com/questions/3728616/boolean-vs-boolean-in-java

반응형