开发者

about intern in java

开发者 https://www.devze.com 2023-03-09 22:06 出处:网络
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,

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?

开发者_Python百科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();  
}  
}


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


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().


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号