Programing

Java에서 int가 null 일 수 있습니까?

lottogame 2020. 6. 16. 21:56
반응형

Java에서 int가 null 일 수 있습니까?


Java에 int있을 수 있습니까 null?

예를 들면 다음과 같습니다.

int data = check(Node root);

if ( data == null ) {
 // do something
} else {
 // do something
}

내 목표는을 반환하는 함수를 작성하는 것입니다 int. int노드는 노드의 높이에 저장되며 노드가 없으면 null이되므로 확인해야합니다.

나는 숙제를 위해 이것을하고 있지만이 특정 부분은 숙제의 일부가 아니며, 내가하고있는 일을 극복하는 데 도움이됩니다.

의견에 감사드립니다. 그러나 실제로 코드의 내용을 읽은 사람은 거의 없습니다. 나는이 목표를 달성 할 수있는 다른 방법을 묻고있었습니다. 작동하지 않는 것을 쉽게 알 수있었습니다.


int null이 있지만 반드시 Integer 깡통을 . null 정수를 개봉 할 때는주의해야합니다. 많은 혼동과 머리 긁힘이 발생할 수 있습니다!

예를 들면 다음과 같습니다.

int a = object.getA(); // getA returns a null Integer

당신에게 줄 것이다 NullPointerException오브젝트가 null없는에도 불구하고!

귀하의 질문에 대한 후속 조치를 취하기 위해 값 없음 을 나타내 려면 조사하겠습니다.java.util.Optional<Integer>


아니요. 기본 요소가 아닌 객체 참조 만 null 일 수 있습니다.


알아내는 좋은 방법 :

public static void main(String args[]) {
    int i = null;
}

컴파일을 시도하십시오.


Java에서 int는 기본 유형이며 객체로 간주되지 않습니다. 객체 만 null 값을 가질 수 있습니다. 따라서 귀하의 질문에 대한 대답은 아니오입니다. 그것은 null 일 수 없습니다. 그러나 가장 원시적 인 유형을 나타내는 객체가 있기 때문에 그렇게 간단하지 않습니다.

Integer 클래스는 int 값을 나타내지 만 널값을 보유 할 수 있습니다. check방법 에 따라 정수 또는 정수를 반환 할 수 있습니다.

이 동작은 루비와 같은 좀 더 순수한 객체 지향 언어와는 다릅니다. 여기서 int와 같은 "기본적인 것"도 객체로 간주됩니다.


위의 모든 대답과 함께이 점도 추가하고 싶습니다.

기본 유형의 경우 고정 메모리 크기가 있습니다. 즉 int의 경우 4 바이트가 있고 char의 경우 2 바이트가 있습니다. 메모리 크기가 고정되어 있지 않기 때문에 null은 객체에만 사용됩니다.

기본적으로 우리는

   int a=0;

그리고 아닙니다

   int a=null;

다른 기본 유형과 동일하므로 null은 기본 유형이 아닌 객체에만 사용됩니다.


코드는 컴파일되지 않습니다. Object다음 null과 같이 완전한 사람 만있을 수 있습니다 Integer. 다음은 null을 테스트 할 수있는 경우를 보여주는 기본 예입니다.

Integer data = check(Node root);

if ( data == null ) {
 // do something
} else {
 // do something
}

반면 check()에 return으로 선언 되면 결코int없으며null 전체 if-else블록이 불필요합니다.

int data = check(Node root);

// do something

autoboxing 문제는 check()return으로 선언 된 경우에도 적용되지 않습니다 int. 반환 된 경우 대신에 할당 할 때 Integer위험 NullPointerException수 있습니다 . 그것을 블록 으로 할당 하고 블록을 사용하는 것은 실제로 필수적이었습니다.intIntegerIntegerif-else

오토 박싱에 대한 자세한 내용은 이 Sun 안내서를 확인하십시오 .


우리가 할 수있는 것처럼 int i선언하는 대신 선언 Integer i할 수 있습니다.i=null;

Integer i;
i=null;

정수 객체가 가장 좋습니다. 프리미티브를 사용해야하는 경우 사용 사례에없는 값을 사용할 수 있습니다. 사람들에게는 음높이가 존재하지 않으므로

public int getHeight(String name){
    if(map.containsKey(name)){
        return map.get(name);
    }else{
        return -1;
    }
}

No, but int[] can be.

int[] hayhay = null; //: allowed (int[] is reference type)
int   hayno  = null; //: error   (int   is primitive type)
                     //: Message: incompatible types: 
                     //: <null> cannot be converted to int

As @Glen mentioned in a comment, you basically have two ways around this:

  • use an "out of bound" value. For instance, if "data" can never be negative in normal use, return a negative value to indicate it's invalid.
  • Use an Integer. Just make sure the "check" method returns an Integer, and you assign it to an Integer not an int. Because if an "int" gets involved along the way, the automatic boxing and unboxing can cause problems.

Check for null in your check() method and return an invalid value such as -1 or zero if null. Then the check would be for that value rather than passing the null along. This would be a normal thing to do in old time 'C'.


Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.

Eg: Integer i=null;


Since you ask for another way to accomplish your goal, I suggest you use a wrapper class:

new Integer(null);

I'm no expert, but I do believe that the null equivalent for an int is 0.

For example, if you make an int[], each slot contains 0 as opposed to null, unless you set it to something else.

In some situations, this may be of use.

참고URL : https://stackoverflow.com/questions/2254435/can-an-int-be-null-in-java

반응형