Java基礎(chǔ)之包裝類
一、java的包裝類
- 什么是包裝類
對于基本數(shù)據(jù)類型來講,其實(shí)就是一個數(shù)字,但是當(dāng)給基本數(shù)據(jù)類型添加一些屬性 方法和構(gòu)造器,將基本數(shù)據(jù)類型對應(yīng)進(jìn)行一個封裝,就產(chǎn)生了一個新的類,這個類被稱為是包裝類。
那么基本數(shù)據(jù)類型在前面中講過有byte short int long float double char boolean
,也就是將這些進(jìn)行封裝,基本數(shù)據(jù)類型和包裝類的對應(yīng)關(guān)系是怎樣的呢?
基本數(shù)據(jù)類型 | 對應(yīng)的包裝類 |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Char |
boolean | Boolean |
二、Integer包裝類
2.1 Integer類的基本介紹
Integer包裝類,是通過int基本數(shù)據(jù)類型進(jìn)行封裝得到的,可以通過查看java的API說明文檔得到它的基本信息:
Integer包裝類在java.lang中,這將意味著可以直接使用,不需要進(jìn)行導(dǎo)包
Integer類被final修飾符修飾,那么這個類不可以有子類,不能被繼承。
2.2 Integer類的屬性
package cn.zhz.Instance; public class Test02 { public static void main(String[] args) { //屬性 System.out.println(Integer.MAX_VALUE); System.out.println(Integer.MIN_VALUE); //物極必反:超出了Int類型的范圍 System.out.println(Integer.MAX_VALUE + 1); System.out.println(Integer.MIN_VALUE - 1); } }
2.3 Integer類的構(gòu)造器
package cn.zhz.Instance; public class Test03 { public static void main(String[] args) { Integer i1 = new Integer(13); System.out.println(i1.toString()); Integer i2 = new Integer("12"); System.out.println(i2); } }
三、自動裝箱和自動拆箱
package cn.zhz.Instance; public class Test04 { public static void main(String[] args) { //自動裝箱:int-->Integer Integer i = 12; System.out.println(i); //自動拆箱:Integer-->int Integer i2 = new Integer(123); int num = i2; System.out.println(num); } }
四、Integer包裝類的方法
類型 | 方法 | 方法的說明 | 返回值 |
int | compareTo() | 比較兩個整數(shù)對象的數(shù)值。 | 只返回三個值,要么是0 -1 1 |
boolean | equals() | 將此對象與指定對象進(jìn)行比較。 | 返回true或者是false |
int | intValue() | 以整數(shù)形式返回此整數(shù)的值。 | |
static int | parseInt() | 將輸入的String類型的數(shù)據(jù)轉(zhuǎn)換成int類型的數(shù)據(jù) | |
String | toString() | 返回表示此整數(shù)值的字符串對象。 |
package cn.zhz.Instance; public class Test05 { public static void main(String[] args) { //compareTo():只返回三個值,要么是0 -1 1 Integer i1 = new Integer(6); Integer i2 = new Integer(12); System.out.println(i1.compareTo(i2));//return (x < y) ? -1 ((x == y) ? 0 : 1) //equals():Integer是對object中的equals方法進(jìn)行了重寫,比較的是底層封裝的那個value的值 //Integer對象是通過new關(guān)鍵字來創(chuàng)建對象 Integer i3 = new Integer(12); Integer i4 = new Integer(12); System.out.println(i3 == i4);//false 因?yàn)?=比較的是兩個對象的地址 boolean flag = i3.equals(i4); System.out.println(flag); //Integer對象是通過自動裝箱來完成的 Integer i5 = 12; Integer i6 = 12; System.out.println(i5.equals(i6));//true System.out.println(i5 == i6); /* * 如果自動裝箱在-128~127之間,那么比較的就是具體的數(shù)值,否則,比較的就是對象的地址 * */ //intvalue(): Integer i7 = 130; int i = i7.intValue(); System.out.println(i); //parseInt(String s):String -->int int i8 = Integer.parseInt("12"); System.out.println(i8); //toString(): Integer i10 = 130; System.out.println(i10.toString()); } }
到此這篇關(guān)于Java基礎(chǔ)之包裝類的文章就介紹到這了,更多相關(guān)java包裝類內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!