zoukankan      html  css  js  c++  java
  • java 包装类

    1 为什么需要包装类(Wrapper Class)
    Java 并不是纯面向对象的语言。Java 语言是一个面向对象
    的语言,但是 Java 中的基本数据类型却是不面向对象的。但
    是我们在实际使用中经常需要将基本数据转化成对象,便于
    操作。比如:集合的操作中。 这时,我们就需要将基本类
    型数据转化成对象!

    2 包装类和基本数据类型的对应关系:包装类继承自java.lang

    3包装类的继承关系

    4 包装类的基本操作
    以 Integer 举例

    (1)int -> Integer new Integer(primitive)
    (2)Integer -> int Integer 对象.xxxValue()
    (3)Integer -> String Integer 对象.toString()
    (4)String -> Integer new Integer(String str)
    (5)int -> String String.valueOf(primitive)
    (6)String -> int Integer.parseXxx()

    public class TestInteger {
        public static void main(String[] args) {
            
            Integer i1=new Integer(123);
            Integer i2=new Integer("123");
            System.out.println("i1==i2:"+(i1==i2)); //false  比较内存
            System.out.println("i1.equals(i2):"+i1.equals(i2));//true 比较内容
            System.out.println(i2.toString());//123 说明Integer类重写了toString方法
            Integer i3=new Integer(128);
            
            //compare源码---return (x < y) ? -1 : ((x == y) ? 0 : 1);
            System.out.println(i1.compareTo(i3));//-1
            System.out.println(i1.compareTo(i2));//0
            System.out.println(i3.compareTo(i2));//1
            
            //(1)Integer-->int     包装类对象.intValue()
            int i=i1.intValue();
            System.out.println(Integer.max(10, 20));//调用的是Math.max()方法
            
            //(2)int-->Integer
            Integer i4=Integer.valueOf(123);
            
            //(3)String -->int      包装类类名.parseInt(String s)
            int ii=Integer.parseInt("234");
            
            //(4)int-->String
            String str=ii+"";
            String s=String.valueOf(ii);
            
            //(5)String-->Integer;
            Integer i5=new Integer("345");
            
            //(6)Integer-->String
            String ss=i5.toString();
            System.out.println(ss);        
        }
    }
    View Code

    5.自动装箱和拆箱

    自动装箱:基本类型自动地封装到与它相同的类型的包装类中
    Integer i=100;
    编译器调用了 valueOf()方法
    Integer i=Integer.valueOf(100);

    Integer 中的缓存类 IntegerCache
    Cache 为[-128,127],IntegerCache 有一个静态的 Integer 数
    组,在类加载时就将-128 到 127 的 Integer 对象创建了,并
    保存在 cache 数组中,一旦程序调用 valueOf 方法,如果取
    的值是在-128 到 127 之间就直接在 cache 缓存数组中去取
    Integer 对象,超出范围就 new 一个对象。

    即[-128,127]的Integer对象地址相同

    自动拆箱:包装类对象自动转换成基本类型数据
    int a=new Integer(100);
    编译器为我们添加了
    int a=new Integer(100).intValue();

  • 相关阅读:
    科目一考试顺口溜 假一吊二撤三醉五逃终身酒犯罪
    Intellij IDEA 关闭和开启自动更新提示
    Spring注解之@Autowired:装配构造函数和属性
    Spring注解之@Autowired:Setter 方法上使用@Autowired注解
    Spring注解之@Autowired组件装配
    Spring注解之@Autowired:注入Arrays, Collections, and Maps
    SQL语句between and边界问题
    Spring中几个最常见的注解
    编辑距离(C++)
    回溯法解N皇后问题
  • 原文地址:https://www.cnblogs.com/bfcs/p/10348277.html
Copyright © 2011-2022 走看看