먼저 테스트 결과를 보자 :
/*public static void main (String [] args) {정수 a = 128, b = 128; 정수 C = 127, d = 127; System.out.println (a == b); // false system.out.println (c == d); // true}*//*public static void main (String [] args) {integer int1 = integer.valueof ( "100"); 정수 int2 = integer.valueof ( "100"); System.out.println (int1 == int2); // true}*/public static void main (String [] args) {integer int1 = integer.valueof ( "300"); 정수 int2 = integer.valueof ( "300"); System.out.println (int1 == int2); // false}JDK의 소스 코드는 다음과 같습니다.
공개 정적 정수 valuef (문자열 s)는 numberformatexception {return integer.valueof (parseint (s, 10)); } 공개 정적 정수 값 (int i) {if (i> = integercache.low && i <= integercache.high) return integercache.cache [i + (-integercache.low)]; 새로운 정수 (I)를 반환합니다. }나는 내부에 또 다른 미스터리가 있다는 것을 알았고 IntegerCache 수업이있었습니다.
개인 정적 클래스 integercache {정적 최종 int low = -128; 정적 최종 INT High; 정적 최종 정수 캐시 []; static {// 높은 값은 int h = 127 특성으로 구성 될 수 있습니다. 문자열 integercachehighpropvalue = sun.misc.vm.getSavedProperty ( "java.lang.integer.integercache.high"); if (integercachehighpropvalue! = null) {try {int i = parseint (integercachehhighpropvalue); i = math.max (i, 127); // 최대 배열 크기는 정수입니다 .max_value h = math.min (i, integer.max_value- (-low) -1); } catch (numberformatexception nfe) {// 속성을 int로 구문 분석 할 수없는 경우 무시하십시오. }} High = H; 캐시 = 새 정수 [(High -Low) + 1]; int j = 낮음; for (int k = 0; k <cache.length; k ++) 캐시 [k] = 새 정수 (j ++); // 범위 [-128, 127]는 내재화되어야합니다 (JLS7 5.1.7) assert integercache.high> = 127; } private integercache () {}}정수는 모든 정수를 -128에서 127 (조정 가능)로 인스턴스화 한 것으로 나타났습니다.
이것은 답을 설명합니다. 이 범위에서 얼마나 많은 정수를 생성하든 모두 동일한 객체를 생성하기 위해 가치를 사용합니다.
그러나 왜 JDK는 이런 식으로 그렇게 많은 일을해야합니까? 그것에 대해주의 깊게 생각합시다. Taobao의 대부분의 제품은 100 위안 미만의 가격입니다. 하루에 백엔드 서버에서 몇 개의 정수가 사용됩니까? IntegerCache를 사용하면 새로운 시간을 줄이고 효율성을 향상시킵니다. 동시에 JDK는 캐시 고값 구성 가능성을 제공합니다.
이것은 의심 할 여지없이 유연성을 향상시키고 JVM의 최적화를 용이하게합니다.
요약
위의 내용은 정수 IntegerCache 소스 코드를 읽는 것에 대한이 기사의 모든 내용입니다. 모든 사람에게 도움이되기를 바랍니다. 관심있는 친구는이 사이트의 다른 관련 주제를 계속 참조 할 수 있습니다. 단점이 있으면 메시지를 남겨 두십시오. 이 사이트를 지원해 주신 친구들에게 감사드립니다!