奇怪的Java题:为什么1000 == 1000返回为False,而100 == 100会返回为True?-控件新闻-慧都控件网



奇怪的Java题:为什么1000 == 1000返回为False,而100 == 100会返回为True?-控件新闻-慧都控件网

这是我们今天要讨论的话题,因为我觉得它非常的有趣。

如果你运行如下代码:

1
2
3
4
Integer a = 1000, b = 1000
System.out.println(a == b);//1
Integer c = 100, d = 100
System.out.println(c == d);//2

你会得到以下运行结果:

1
2
false
true

我们知道,如果两个引用指向同一个对象,那么==就成立;反之,如果两个引用指向的不是同一个对象,那么==就不成立,即便两个引用的内容是一样的。因此,结果就会出现false。

这是非常有趣的地方。如果你查看Integer.java类,你会找到IntegerCache.java这个内部私有类,它为-128到127之间的所有整数对象提供缓存。

这个东西为那些数值比较小的整数提供内部缓存,当进行如此声明时:

1
Integer c = 100;

它的内部就是这样的:

1
Integer i = Integer.valueOf(100);

如果我们观察valueOf()类函数,我们可以看到

1
2
3
4
5
public static Integer valueOf(int i) {
      if (i >= IntegerCache.low && i
          return IntegerCache.cache[i + (-IntegerCache.low)];
      return new Integer(i);
    }

如果值在-128到127之间,它就会返回该缓存的实例。

因此。。。

1
Integer c = 100, d = 100;

两者指向同样的对象。

这就是为什么这段代码的结果为true了:

1
System.out.println(c == d);

现在你可能会问,为什么会为-128到127之间的所有整数设置缓存?


Read full article from 奇怪的Java题:为什么1000 == 1000返回为False,而100 == 100会返回为True?-控件新闻-慧都控件网


No comments:

Post a Comment

Labels

Algorithm (219) Lucene (130) LeetCode (97) Database (36) Data Structure (33) text mining (28) Solr (27) java (27) Mathematical Algorithm (26) Difficult Algorithm (25) Logic Thinking (23) Puzzles (23) Bit Algorithms (22) Math (21) List (20) Dynamic Programming (19) Linux (19) Tree (18) Machine Learning (15) EPI (11) Queue (11) Smart Algorithm (11) Operating System (9) Java Basic (8) Recursive Algorithm (8) Stack (8) Eclipse (7) Scala (7) Tika (7) J2EE (6) Monitoring (6) Trie (6) Concurrency (5) Geometry Algorithm (5) Greedy Algorithm (5) Mahout (5) MySQL (5) xpost (5) C (4) Interview (4) Vi (4) regular expression (4) to-do (4) C++ (3) Chrome (3) Divide and Conquer (3) Graph Algorithm (3) Permutation (3) Powershell (3) Random (3) Segment Tree (3) UIMA (3) Union-Find (3) Video (3) Virtualization (3) Windows (3) XML (3) Advanced Data Structure (2) Android (2) Bash (2) Classic Algorithm (2) Debugging (2) Design Pattern (2) Google (2) Hadoop (2) Java Collections (2) Markov Chains (2) Probabilities (2) Shell (2) Site (2) Web Development (2) Workplace (2) angularjs (2) .Net (1) Amazon Interview (1) Android Studio (1) Array (1) Boilerpipe (1) Book Notes (1) ChromeOS (1) Chromebook (1) Codility (1) Desgin (1) Design (1) Divide and Conqure (1) GAE (1) Google Interview (1) Great Stuff (1) Hash (1) High Tech Companies (1) Improving (1) LifeTips (1) Maven (1) Network (1) Performance (1) Programming (1) Resources (1) Sampling (1) Sed (1) Smart Thinking (1) Sort (1) Spark (1) Stanford NLP (1) System Design (1) Trove (1) VIP (1) tools (1)

Popular Posts