Java自学笔记—包装类
概述
8种基本数据类型对应8种包装类,其中Boolean
和Character
的父类为Object
,其余的父类为Number
,都实现了CharSequence
和Comparable
接口,实现CharSequence接口可以串行化,即网络传输。Comparable接口可以使得两个可以相互比较
装箱和拆箱
/**
* @author Lspero
* @version 1.0
*/
public class Integer01 {
public static void main(String[] args) {
//装箱和拆箱
//jdk5之前是手动拆箱装箱
//手动装箱
int n1 = 100;
Integer integer = new Integer(n1);
Integer integer1 = Integer.valueOf(n1);
//手动拆箱
int i = integer.intValue();
//自动装箱
int n2 = 100;
Integer integer2 = n2;//底层为Integer.ValueOf()
//自动拆箱
int n3 = integer2; //调用intValue()
}
}
自动装箱细节
/**
* @author Lspero
* @version 1.0
*/
public class WrapperExercise02 {
public static void main(String[] args) {
int i = new Integer(1);
int j = new Integer(1);
// == 判断两个对象是否是同一个对象
System.out.println(i == j);//new分别创立两个对象,因此不相等,flase
/*
public static Integer valueOf(int i) {
//-128~127
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
* */
Integer m = 1;//自动装箱 底层为Integer.ValueOf(),查看源码,-128~127直接返回一个对象
Integer n = 1;
System.out.println(m == n);//true
Integer x = 128;//超过-128~127,要重新创建对象
Integer y = 128;
System.out.println(x == y);//false
Integer q = 127;
int num = 127;
System.out.println(q == num);//存在基本数据类型,因此==判断值是否相等,true
}
}
String与Integer转化
String 有属性 Private finally char value[]; 用于存放字符串内容,是finally类型,不可以修改(地址,即不能指向新地址,但值可以修改)
package com.hz.wrapper_;
/**
* @author Lspero
* @version 1.0
*/
public class WrapperVSString {
public static void main(String[] args) {
//包装类->String
Integer i = 10;
//3种
String str1 = i + "";
String str2 = i.toString();
String s = String.valueOf(i);
//String->包装类
String str4 = "12345";
//2种
Integer i2 = Integer.parseInt(str4);
Integer integer = new Integer(str4);
}
}
总结
CharSequence
接口可以串行化,Comparable
接口对象之间可以相互比较- 自动装箱
Integer integer2 = n2;//底层为Integer.ValueOf()
==
判断两个对象是否是同一个对象,即内存中地址是否相等,equals
则判断值是否相等- Integer自动装箱时,若数值在 -128~127直接返回一个对象,否则会new一个对象
- String 有属性
Private finally char value[];
,不能修改地址