Java小白踩坑录 - Integer & String 揭秘

Integer

public static void main(String[] args) {
    Integer num1=56;
    Integer num2=56;
    System.out.println(num1==num2);
    System.out.println(num1.equals(num2));
    
    Integer num3=34567;
    Integer num4=34567;
    System.out.println(num3==num4);
    System.out.println(num3.equals(num4));
    
    Integer num21=-56;
    Integer num22=-56;      
    System.out.println(num21==num22);
    System.out.println(num21.equals(num22));
    
    Integer num23=-34567;
    Integer num24=-34567;
    System.out.println(num23==num24);       
    System.out.println(num23.equals(num24));
}

// 答案
true
true
false
true
true
true
false
true

解析

“首先,== 指的是对象的比较,equals 是的比较;其次,Integer 类型的赋值表达式 = 有一个装箱的过程,在装箱时先对 int 得值做判断,如果值在【-128,127】之间时返回创建好的对象,否则返回新的对象,JLS5 有介绍,源码里也有实现”。

/**
 * Returns an {@code Integer} instance representing the specified
 * {@code int} value. If a new {@code Integer} instance is not
 * required, this method should generally be used in preference to
 * the constructor {@link #Integer(int)}, as this method is likely
 * to yield significantly better space and time performance by
 * caching frequently requested values.
 *
 * This method will always cache values in the range -128 to 127,
 * inclusive, and may cache other values outside of this range.
 *
 * @param i an {@code int} value.
 * @return an {@code Integer} instance representing {@code i}.
 * @since 1.5
 */
 public static Integer valueOf(int i) {
     if (i >= IntegerCache.low && i <= IntegerCache.high)
         return IntegerCache.cache[i + (-IntegerCache.low)];
     return new Integer(i);
 }

String

String hello="hello world!"; 
String hello1=new String("hello world!");
System.out.println(hello==hello1); //1
String hello2="hello world!";
System.out.println(hello==hello2); //2
String append="hello"+" world!";
System.out.println(hello==append); //3
final String pig = "length: 10";
final String dog = "length: " + pig.length();
System.out.println(pig==dog); //4
final String dog1 = ("length: " + pig.length()).intern();
System.out.println(pig==dog1); //5
System.out. println("Animals are equal: "+ pig == dog);//6

// 答案
false
true
true
false
true
false

解析

通过常量表达式运算得到的字符串是在编译时计算得出的,并且之后会将其当作字符串常量对待;在运行时通过连接运算得到的字符串是新创建的,因此要区别对待。其它如可以通过显示的限定运算得到的字符串为字符串常量,String.intern 方法可以 " 限定,操作符的优先级也可以通过 JLS(Java language Specification) Java 编程规范这本书中可以查到。”

“再总结一下,不管是 Integer、Long、Char、Short、Double、Float、String 都涉及到一个拆箱装箱的过程,各自的规则也略有差异,故要仔细看看 JLS 的定义”。

发布了952 篇原创文章 · 获赞 1820 · 访问量 89万+

猜你喜欢

转载自blog.csdn.net/Dream_Weave/article/details/105423367
今日推荐