>  기사  >  Java  >  Integer.valueOf, Integer.parseInt, 새 정수

Integer.valueOf, Integer.parseInt, 새 정수

巴扎黑
巴扎黑원래의
2017-06-26 10:41:091571검색

먼저 아래 결과를 보세요

1.System.out.println(127==127); //true , int type compare2.System.out.println(128==128); //true , int type compare3.System.out.println(new Integer(127) == new Integer(127)); //false, object compare4.System.out.println(Integer.parseInt("128")==Integer.parseInt("128")); //true, int type compare5.System.out.println(Integer.valueOf("127")==Integer.valueOf("127")); //true ,object compare, because IntegerCache return a same object6.System.out.println(Integer.valueOf("128")==Integer.valueOf("128")); //false ,object compare, because number beyond the IntegerCache7.System.out.println(Integer.parseInt("128")==Integer.valueOf("128")); //true , int type compare

Explanation

int 정수 상수를 비교할 때 ==는 값 비교이므로 1,2는 true를 반환합니다. 1, 2는 값 비교입니다.

new Integer()는 매번 새로운 Integer 객체를 생성하므로 3은 false를 반환합니다. 3은 물체 비교이다.

Integer.parseInt는 매번 int 상수를 구성하므로 4가 true를 반환합니다. 4는 값 비교이다.

Integer.valueOf는 기본적으로 -128~127 사이에 있으면 캐시에 있는 기존 객체(존재하는 경우)를 반환하므로 5는 true를 반환하고 6은 false를 반환합니다. 5와 6은 물체 비교이다.

7번째는 특별합니다. int와 Integer 간의 비교입니다. 결과는 값 비교이며 true를 반환합니다.

요약

정수 비교의 경우 먼저 값 비교인지 객체 비교인지 확인합니다. 값 비교 중 하나가 값이면 값 비교입니다. 객체 비교는 객체가 어떻게 구성되는지에 따라 달라집니다. new Integer 메소드를 사용하면 매번 새로운 객체가 생성됩니다. 두 개의 new Integer를 비교하면 반드시 false가 반환됩니다. 범위가 -128에서 127 사이이면 동일한 값으로 생성된 객체는 동일한 객체입니다. ==는 비교 후 true를 반환하고, 그렇지 않으면 false를 반환합니다.

그러므로 값 비교 ==에 대해 걱정하지 마세요. 정수 비교의 경우 객체 내용을 비교하기 위해 equals 메서드를 사용하는 것이 가장 좋습니다. 물론 먼저 정수가 null이 아닌지 확인하세요.

지식 확장

Integer.valueOf 소스 코드 분석

1. 우리가 호출하는 Integer.valueOf 메소드는 먼저 ParseInt를 호출하여 이를 int 값으로 변환한 다음 자체 오버로드된 메소드를 조정합니다

public static Integer valueOf(String s) throws NumberFormatException {return Integer.valueOf(parseInt(s, 10));
    }

2. Integer.valueOf 오버로드된 메서드는 i 값의 크기에 따라 캐시에서 Integer 개체를 검색할지 여부를 결정합니다.

 public static Integer valueOf(int i) {if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);
    }

3 Integer의 생성자는 매우 간단합니다

  public Integer(int value) {this.value = value;
    }

4. 정적 클래스는 Integer 내부 클래스이며 세 가지 속성(캐시된 정수 배열 + 캐시 범위 집합)

private static class IntegerCache {static final int low = -128;static final int high;static final Integer cache[];static {// high value may be configured by property(最大值可配置)int h = 127;
            String integerCacheHighPropValue =sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); //读取VM参数if (integerCacheHighPropValue != null) {try {int i = parseInt(integerCacheHighPropValue); //配置值转换成int数值i = Math.max(i, 127);  //和127比较,取较大者// Maximum array size is Integer.MAX_VALUE(控制缓存数组的大小,最大为整型的最大值,这样一来,h值就必须小于整型最大值,因为要存 -128~0这129个数嘛)h = Math.min(i, Integer.MAX_VALUE - (-low) -1); //实际就是 h=Math.min(i,Integer.MAX_VALUE-129),正整数能缓存的个数} catch( NumberFormatException nfe) {// If the property cannot be parsed into an int, ignore it.                }
            }
            high = h;

            cache = new Integer[(high - low) + 1]; //构造缓存数组int j = low;for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);  //将一些int常量缓存进Integer对象数组缓存中去// range [-128, 127] must be interned (JLS7 5.1.7)assert IntegerCache.high >= 127; //如果小于127,抛异常}private IntegerCache() {}
    }

위의 Integer.valueOf 소스 코드를 읽은 후 기본 Integer 캐시 int 상수 풀을 구성할 수 있음을 알 수 있습니다. 예, 구성 방법은 VM 매개변수를 추가하고 다음을 추가하는 것입니다: -Djava.lang.Integer.IntegerCache.high=200

Intellij IDEA 실행 구성의 VM 옵션 옵션에 매개변수를 추가하기만 하면 됩니다.

위 내용은 Integer.valueOf, Integer.parseInt, 새 정수의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.