about intern in java

无人久伴 提交于 2019-11-30 21:37:45

问题


my question is if intern is working with string and string having a SPC(string pool constant) for it and intern concept also working with integer also, so is there any integer pool constant?if not then how its working?

class InternExample  
{  
 public void print()  
{    
 Integer i=10;  
 Integer j=10;  
 String c="a";  
  String s="a";  
 System.out.println(i==j);// prints true  
 System.out.println(c==s);//prints true  
}  
 public static void main(String args[])  
{  
  new InternExample().print();  
}  
}

回答1:


Added to @Joachim Sauer's answer, we can change the upper bound cache value.

Some of the options are

  1. -Djava.lang.Integer.IntegerCache.high=value
  2. -XX:AutoBoxCacheMax=value
  3. -XX:+AggressiveOpts

Link : Java Specialist




回答2:


Auto-boxing uses a cache of common values, as defined in § 5.1.7 Boxing Conversion of the JLS:

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Note that this is not called "interning", however. That term is only used for what is done to String literals and what can explicitly be done using String.intern().




回答3:


Beware of your "equality assumptions". For example, with integers:

    Integer a = 69;
    Integer b = 69;
    System.out.println(a == b); // prints true
    Integer c = 1000;
    Integer d = 1000;
    System.out.println(c == d); // prints false

This is due to the internal implementation of Integer, having pre-existing objects for integer for small values (from -127 to 128 i think). However, for bigger integers, a distinct object Integer will be created each time.

Same goes for your Strings, literal strings in your source code will all be linked to the same object by the compiler ...he's smart enough to do that. However, when you'll read a string from a file, or create/manipulate some string at runtime, they will not be equal anymore.

    String a = "x";
    String b = "x";
    String c = new String("x");
    System.out.println(a == b); // prints true
    System.out.println(a == c); // prints false


来源:https://stackoverflow.com/questions/6199165/about-intern-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!