zoukankan      html  css  js  c++  java
  • Java基础 【自动装箱和拆箱、面试题】

    JDK 1.5 (以后的版本)的新特性自动装箱和拆箱

    1. 自动装箱:把基本类型转换为包装类类型
    int a =10;
    Integer i = new Integer(a);

    Integer value = 10;
    为什么基本类型就能直接转化为Integer ,Integer 不应该是new出来的吗
    内部会自动的 new Integer(10) 自动装箱


    2. 自动拆箱: 把包装类型转换为基本类型
    Integer value2 = new Integer(120);
    int a = value2;
    对象赋值给基本数据类型,为什么会不报错,因为内部会调用 value2.intValue() 这种就是自动拆箱

    举一反三

    Double d1 = 9.14 //内部会自动new一个Double 然后传递进去


    new 出来的东西 每个都会分配一个内存地址

    拆箱:devaning
    装箱:


    装箱拆箱面试题: 考点(Integer内部装箱的内部实现)

    看程序写结果
    1.

    Integer value1 = new Integer(97);
    Integer value2 = new Integer(97);
    System.out.println(value1 == value2);
    System.out.println(value.equals(value2)); //这个就是比较值
    System.out.println("-------------------");

    答案 : false true


    2. 自动装箱,如果值一样、地址也一样

    Integer value3 = 127; //自动装箱
    Integer value4 = 127;
    System.out.println(value3 == value4);
    System.out.println(value3.equals(value4)); //这个也是比较值


    答案:true true


    `3.

    Integer value5 = 128;
    Integer value6 = 128;
    System.out.println(value5==value6); //false
    System.out.println(value5.equals(value6)); //true

    答案: false true



    总结: 自动装箱,范围在 -128 ~ 127 【256个数字 】的地址是一样的,其他范围地址不一样
    -128 到 127 之间的有个自动装箱的缓存池 如果不在这个范围,就会使用new 新创建

  • 相关阅读:
    SNMP++
    临界区,互斥量,信号量,事件的区别
    2015 年最棒的 5 个 HTML5 框架(转)
    java.lang.OutOfMemoryError: PermGen space及其解决方法
    java.net.SocketException: Unrecognized Windows Sockets error: 0: JVM_Bind
    eclipse安装tomcat插件
    (转)Activity的跳转与传值
    Android SDK下载和更新失败的解决方法
    Android客户端WebView控件与Javascript交互
    SCI期刊
  • 原文地址:https://www.cnblogs.com/kangxinxin/p/9689701.html
Copyright © 2011-2022 走看看