自动装箱、拆箱和String的相关问题

来源:互联网 发布:2016淘宝报名双11入口 编辑:程序博客网 时间:2024/04/27 10:36

1、自动装箱将基本数据类型转化为对应的封装类型。

自动拆箱就是将对象重新转化为基本数据类型,在进行运算的时候自动拆箱。

Integer num = 10;//装箱,相当于建立一个对象。
Integer num = 10;System.out.print(num--);//进行计算时隐含的有自动拆箱

2、对于Integer num=一个数,在自动装箱时对于值从–128到127之间的值,它们被装箱为Integer对象后,会存在内存中被重用,始终只存在一个对象(Byte、Short、Integer、Long适用,Float、Double不适用)。 而如果超过了从–128到127之间的值,被装箱后的Integer对象并不会被重用,即相当于每次装箱时都新建一个 Integer对象。

对于Integer a=new Integer(一个数),每次都要创建对象,不管这个数的大小。

public class In {public static void main(String[] args) {Integer a=100;Integer b=100;System.out.println(a==b);//ture}}
public class In {public static void main(String[] args) {Integer a=3000;Integer b=3000;System.out.println(a==b);//false}}
public class In {public static void main(String[] args) {Integer a=new Integer(100);Integer b=100;System.out.println(a==b);//<span style="font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;">false</span>}}
public class In {public static void main(String[] args) {Integer a=100;int b=100;System.out.println(a==b);//ture,有运算,自动拆箱,相当于两个基本类型比大小}}

3、这个的自动装箱拆箱不仅在基本数据类型中有应用,在String类中也有应用,比如我们经常声明一个String对象时:

String str = "sl";//代替下面的声明方式String str = new String("sl");
问题String s = new String(“hello”)和String s = “hello”;的区别?

String的值都在方法区的常量池中,前者要在对中创建s对象和常量池中创建hello对象。后者只需要在常量池中创建hello对象;前者会创建2个对象,后者创建1个对象。
看一下程序的结果:
public class St {    public static void main(String[] args) {        String s1 = "hello";        String s2 = "world";        String s3 = "helloworld";        System.out.println(s3 == s1 + s2);// false        System.out.println(s3.equals((s1 + s2)));// true        System.out.println(s3 == "hello" + "world");// true        System.out.println(s3.equals("hello" + "world"));// true           }}
字符串如果是变量相加,先开空间,在拼接。字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否则,就创建。




0 0
原创粉丝点击