• 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();

  • 相关阅读:
    界面间传值
    消息通知中心
    ios外部链接或者app唤起自己的app
    iOS跳转第三方应用举例一号店和京东
    ios 传递JSON串过去 前面多了个等号
    react-native 配置 在mac 上找不到.npmrc
    webView 获取内容高度不准确的原因是因为你设置了某个属性
    WKWebView 加载本地HTML随笔
    关于attibutedText输出中文字符后的英文和数字进行分开解析的问题
    iOS 企业包碰到的问题
  • 原文地址:https://www.cnblogs.com/bfcs/p/10348277.html
Copyright © 2020-2023  润新知