java筆記 Object 包裝類
說明 若方法有多個過載,將會省略個別的程式碼具體實現過程,貼出該過載的宣告.
目錄
Object
toString() equals() hashCode() clone() getClass() finalize() notify() notifyAll() wait()
包裝類
Character
Boolean
Number抽象類
繼承Number的 Integer Long Short Byte
Integer 和 Long 的方法(Integer和Long兩個包裝類中的方法一致)
Integer部分方法詳解
目錄
繼承Number的 Integer Long Short Byte
Object
java中所有類的主線的祖先,所有其他類都由此派生
Object方法有9個方法
toString()
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
equals()
public boolean equals(Object obj) {
return (this == obj);
}
== 檢查同一性 即是否為同一個物件的引用
equals 檢查相等性 ,相等性包括同一性,即 == 是equals 的一種情況
hashCode()
public native int hashCode();
返回一個整數 即物件的雜湊碼 類似於一個物件的簽名或校驗和 由物件的內容而生成
equals返回true的兩個物件的hashCode返回值必須一樣
將物件儲存到Hashtable(稱為字典或關聯陣列)是會用到雜湊碼
Object的預設實現並沒有真正實現這一方案
clone()
protected native Object clone() throws CloneNotSupportedException;
為使自己是可以複製的 物件必須實現java.lang.Cloneable介面 (標誌介面,表此物件希望得到複製)
若物件不可復值則丟擲CloneNotSupportedException異常
1. = 使用等號賦值 只是將引用指向統一物件
2. clone() 使用clone克隆方法 得到複製 且為淺拷貝,
3.深拷貝
getClass()
public final native Class<?> getClass();
返回次Object的執行時類型別。
不可重寫,要呼叫的話,一般和getName()聯合使用,如getClass().getName();
finalize()
protected void finalize() throws Throwable { }
子類可以覆蓋該方法以實現資源清理工作,GC在回收物件之前呼叫該方法
不同於c++中的解構函式 C++中的解構函式呼叫的時機是確定的(物件離開作用域或delete掉),但Java中的finalize的呼叫具有不確定性 ,它最主要的用途是回收特殊渠道申請的記憶體。比如調如非ava程式碼
notify()
public final native void notify();
喚醒在該物件上等待的某個執行緒。
notifyAll()
public final native void notifyAll();
喚醒在該物件上等待的所有執行緒。
wait()
public final void wait() throws InterruptedException {
wait(0);
}
//timeout 等待的最長時間毫秒 nanos - 額外時間 納秒
public final native void wait(long timeout) throws InterruptedException;
public final void wait(long timeout, int nanos) throws InterruptedException {
if (timeout < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}
if (nanos > 0) {
timeout++;
}
wait(timeout);
}
1000000*timeout+nanos (納秒) 1納秒(ns)=1e-6毫秒(ms)
wait()會讓出物件鎖,同時,當前執行緒休眠,等待被喚醒,如果不被喚醒,就一直等在那兒。
notify()並不會讓當前執行緒休眠,但會喚醒休眠的執行緒。
包裝類
基本資料型別 | 對應的包裝類 |
---|---|
boolean | Boolean |
char | Character |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
基本型別 與 包裝類的轉換
基本型別 --> 包裝類的轉換 :java9將建構函式已過時 推薦使用 靜態方法 :
public static 包裝類 valueOf(包裝類對應的基本型別)
public static 包裝類 valueOf(String s)
基本型別 <-- 包裝類的轉換 xxxValue() 返回對應的基本型別
除Character類為 其他包裝類都有 parsexxx(string)的方法 根據字串返回基本型別值
Integer a = 12; // 自動裝箱
int b = a; //自動拆箱
編譯器將上面轉換成
Integer a = Integer.valueOf(12);
int b = a.intValue();
都重寫了Object中的 equals() hashCode() toString()
包裝類都實現了Comparable介面 ,它只有一個方法 compareTo()
public interface Comparable <T>{
public int compareTo(T o); //小於 .等於 .大於 引數時 返回-1 0 1
}
包裝類(除Boolean類)都定義了常量
MAX_VALUE | 該包裝類對應的基本型別的最大值 |
MIN_VALUE | 該包裝類對應的基本型別的最小值 |
SIZE | 該包裝類對應的基本型別規定的位數 |
BYTES | 該包裝類對應的基本型別規定的位元組數 |
Boolean
public final class Boolean implements java.io.Serializable,
Comparable<Boolean>{
public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
private static final long serialVersionUID = -3665804199014368530L;
public static final Class<Boolean> TYPE = (Class<Boolean>) Class.getPrimitiveClass("boolean");
private final boolean value;
//已過時的建構函式 略
/*
*返回Boolean表示指定boolean值的例項 。
*如果指定的boolean值是true,則此方法返回Boolean.TRUE; 如果是false,則此方法返回Boolean.FALSE。
*如果Boolean不需要新例項,則通常應優先使用此方法,
*而不是建構函式 Boolean(boolean),因為此方法可能會產生明顯更好的空間和時間效能。
*/
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
/*返回Boolean帶有指定字串表示的值的a
*在Boolean返回的代表真值如果字串引數不是null ,是平等的,
*忽略大小寫,字串"true"。否則,返回false值,包括null引數。
*/
public static Boolean valueOf(String s) {
return parseBoolean(s) ? TRUE : FALSE;
}
//將String s的值轉換成 boolean
public static boolean parseBoolean(String s) {
return ((s != null) && s.equalsIgnoreCase("true"));
}
//當存在name值的系統變數存在則返回 true
public static boolean getBoolean(String name) {
boolean result = false;
try {
result = parseBoolean(System.getProperty(name));
} catch (IllegalArgumentException | NullPointerException e) {
}
return result;
}
/*
* String name = "a" ;
* System.setProperty(name, "true");
* System.out.println(Boolean.getBoolean(name));//true
* System.setProperty(name, "fasle");
* System.out.println(Boolean.getBoolean(name));//fasle
*/
}
Boolean類的方法
public static boolean | return |
logicalAnd(boolean a, boolean b) | a && b |
logicalOr(boolean a, boolean b) | a || b |
logicalXor(boolean a, boolean b) | a ^ b |
parseBoolean(String s) | 當s不為空且其值為"true"時返回true (Boolean) |
getBoolean(String name) | 當且僅當以引數命名的系統屬性存在 |
修飾符 | 方法名(引數) | return語句 | 說明 |
public static int | compare(boolean x, boolean y) | (x == y) ? 0 : (x ? 1 : -1) | 兩個引數 0相等 1 大於 -1小於 |
public int | compareTo(Boolean b) | compare(this.value, b.value) | 一個引數 具體實現由compareTo() |
public static String | toString(boolean b) | b ? "true" : "false" | 將Boolean zh轉換成對應的string |
public static Boolean | valueOf(boolean b) | (b ? TRUE : FALSE) | |
public static Boolean | valueOf(String s) | parseBoolean(s) ? TRUE : FALSE | |
public boolean | booleanValue() | value | boolean java.lang.Boolean.value |
public int | hashCode() | value ? 1231 : 1237 | 返回此 1231代表true 1237表示false |
Number抽象類
提供了轉換成 7 種數基本型別的方法
public abstract class Number implements java.io.Serializable {
public abstract int intValue();
public abstract long longValue();
public abstract float floatValue();
public abstract double doubleValue();
public byte byteValue() {
return (byte)intValue();
}
public short shortValue() {
return (short)intValue();
}
private static final long serialVersionUID = -8742448824652078965L;
public static int compare(char x, char y) {
return x - y;
}
/*序列化Serializable介面,
*序列化操作的時候系統會把當前類的serialVersionUID寫入到序列化檔案中
*當反序列化時系統會去檢測檔案中的serialVersionUID,
*判斷它是否與當前類的serialVersionUID一致,
*如果一致就說明序列化類的版本與當前類版本是一樣的,
可以反序列化成功,否則失敗。
*/
繼承Number的 Integer Long Short Byte
public方法 程式碼以Integer的相關方法程式碼舉例
Integer 和 Long 都有方法Integer 和Long兩個包裝類方法一致 |
xx對應的基本型別 Xx對應的包裝類 |
文件建議:使用parseXxx ( String ) 一個字串轉換為 或者使用valueOf ( String ) 一個字串轉換為 |
|
文件建議: valueOf( xxx )
|
|
static int bitCount(xx i) | 返回該數值對應的二進位制中 1 的個數 |
static int compareUnsigned(xx x, xx y) | 將引數x y看作無符號數並比較其大小 |
static Xx getXx(String nm) | 確定指定名稱的系統屬性的整數值。 |
static Xx getXx(String nm, xx val) | 確定指定名稱的系統屬性的整數值。 |
static Xx getXx(String nm, Xx val) | 確定指定名稱的系統屬性的整數值。 |
static xx highestOneBit(xx i) | 先將 i 除了前導0的剩下部分全置1 return i - (i >>> 1);//前導0_1_0..0 |
static xx lowestOneBit(xx i) | return i&-i; 返回二進位制數最低位權值 1010:10 100100: 100 111: 1 |
static int numberOfLeadingZeros(xx i) | 返回前導0的個數 |
static int numberOfTrailingZeros(xx i) | 返回後導0的個數 |
static xx reverse(xx i) | 按位逆置 例:3210-2301-0123 相鄰1位相互交換 相鄰2位 相鄰4位 0~ i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555; i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333; i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f; i = (i << 24) | ((i & 0xff00) << 8) |((i >>> 8) & 0xff00) | (i >>> 24);//0~7與24~31、8~15與16~23相互交換 |
static xx reverseBytes(xx i) | ((i >>> 24) ) | ((i >> 8) & 0xFF00) | ((i << 8) & 0xFF0000) | ((i << 24));//按位元組交換4與1 2與3交換 |
static xx rotateLeft(xx i, int distance) | (i << distance) | (i >>> -distance) 迴圈左移 迴圈方向與 -distance的操作方向相同 |
static xx rotateRight(xx i, int distance) | (i >>> distance) | (i << -distance)迴圈右移 n為自然數 [-distance]後5+distance=32*n -distance實際移動看後5位 |
static int signum(xx i) | (i >> 31) | (-i >>> 31)返回符號位 |
static String toBinaryString(xx i) | xx ->String(xx的二進位制形式) |
static String toOctalString(xx i) | xx ->String(xx的八進位制形式) |
static String toString(int i, int radix) | xx ->String(xx的radix進位制形式) |
static xx parseUnsignedXx (String s) | String->xx(十進位制形式) |
static xx parseUnsignedXx (String s, int radix) | String->xx(radix進位制形式) |
static Xx divideUnsigned(xx dividend, xx divisor) |
(int)(toUnsignedLong(dividend) / toUnsignedLong(divisor))求商 |
static xx remainderUnsigned(xx dividend, xx divisor) |
(int)(toUnsignedLong(dividend) %toUnsignedLong(divisor))求餘數 |
Byte Short Integer Long Float Double
Byte | Short | Integer | Long | Float | Double | ||||||||
static int toUnsignedInt(xx x) | 0xff | 0xffff | × | × | × | × | ((int) x) & 0xffff Short中 | ||||||
static long toUnsignedLong(xx x) | 0xffL | 0xffffL | √ | × | × | × | ((long) x) & 0xffffL Short中 | ||||||
static xx sum(xx a, xx b) | × | × | √ | √ | √ | √ | 求和 | ||||||
static xx max(xx a, xx b) | × | × | √ | √ | √ | √ | 求兩個數之中的最大值max | ||||||
static xx mix(xx a, xx b) | × | × | √ | √ | √ | √ | 求兩個數之中的最小值min | ||||||
static String toHexString(xx i) | × | × | √ | √ | √ | √ | xx ->String(xx的十六進位制形式) | ||||||
static xxx decode(String nm) | √ | √ | √ | √ | Byte Short 呼叫了Integer.decode(nm) 返回valueOf((xx)i) 在Integer Long 中均是自己實現的 1.解析字首對應的進位制2.呼叫xxx.valueOf(xx ,radix) |
||||||||
Double 和Float |
|||||||||||||
xxx表double或float Xxx表Double或Float |
Double 和Float 都有的方法 | ||||||||||||
java9已將此方法標記為已過時 |
文件建議: 使用 valueOf (xxx ) 例如 Float.valueOf( (float) value ) |
||||||||||||
java9已將此方法標記為已過時 |
文件建議:使用parseXxx(String) 將字串轉換為 或者使用valueOf (String ) 將一個字串轉換為Xxx物件 |
||||||||||||
static boolean isFinite(xxx f) | 如果引數是一個有限的浮點數,則返回 | 對於NaN和infinity返回false | |||||||||||
boolean isInfinite() | 如果引數是正無窮大或負無窮大此方法返回true |
否則返回false |
|||||||||||
static boolean isInfinite(xxx v) | |||||||||||||
boolean isNaN() | 如果這個浮點值不是非數字(NAN)方法返回true | 否則返回false | |||||||||||
static boolean isNaN(xxx v) | |||||||||||||
Float獨有的 | double獨有的 | ||||||||||||
|
|||||||||||||
static int floatToIntBits(float value) | static long doubleToLongBits(double value) | hashCode方法呼叫了該方法 | |||||||||||
static int floatToRawIntBits(float value) | static long doubleToRawLongBits(double value) | 返回浮點值的表示形式,並保留非數字(NaN)值。 | |||||||||||
Number繼承類所共有的方法
|
|||||||||||||
static int compare(xx x,xx y) | x>y 1 x==y 0 x<y -1 | 繼承Number抽象類 | |||||||||||
byte byteValue() | 繼承Number抽象類 | ||||||||||||
short shortValue() | 繼承Number抽象類 | ||||||||||||
int intValue() | 繼承Number抽象類 | ||||||||||||
long longValue() | 繼承Number抽象類 | ||||||||||||
float floatValue() | 繼承Number抽象類 | ||||||||||||
double doubleValue() | 繼承Number抽象類 | ||||||||||||
int compareTo(Xx anotherXx) | |||||||||||||
Number繼承類的建構函式均已被java9標記為已過時 | |||||||||||||
static Xx valueOf(xx b) | 8種包裝類 √ | 基本型別->轉換成包裝類 用以代替建構函式Xx(xx value) |
|||||||||||
static Xx valueOf(String s) | 字串 (十進位制)->轉換成包裝類 用以代替建構函式Xx(String s) |
||||||||||||
static Xx valueOf(String s, int radix) | Byte Short Integer Long √ | Float Double × | 字串 ->轉換成包裝類 | ||||||||||
static xx parseXx(String s) | 8種包裝類 √ | 字串->基本型別(十進位制) | |||||||||||
static xx parseXx(String s, int radix) | Byte Short Integer Long √ | Float Double × | 字串->基本型別(radix進位制) | ||||||||||
boolean equals(Object obj) | 繼承Object | ||||||||||||
int hashCode() | 繼承Object | ||||||||||||
static int hashCode(xx value) | |||||||||||||
String toString() | |||||||||||||
static String toString(xx f) | |||||||||||||
Integer
public final class Integer extends Number implements Comparable<Integer> {
//建議使用valueOf ,構造方法已被標記過時
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
public static Integer valueOf(String s, int radix) throws NumberFormatException {
return Integer.valueOf(parseInt(s,radix));
}
parseInt()將字串轉成數字
1.字串與數字的對應關係 string[0]->數字中的高位 string 0-length ->數字 高位-低位
2. 將結果存為負數 , 返回時再做正負變換(負數的邊界的絕對值比正數的大一)
3. [-2147483648 , 2147483647] int範圍
因此對於溢位判斷 應有兩個值作為標誌位
即 limit 表 最大邊界
multmin = limit/ radix ;// limit=-2147483647, radix =16 時,得到 multmin = -134217727 ;//0x7FFFFFF
//multmin的作用 以radix=10 limit=-2147483647 為例 判斷字串例如 String ="9147483647";
//對於limit來說 9147483647明顯溢位 只能正確儲存到 914748364 此時 multmin的作用就顯現了
result < limit + digit
用於判斷2147483649類似的值 limit(為負數)
與result - digit < limit 對比 在數學上是相等的 但考慮int儲存範圍 result < limit + digit是正確的
result - digit 的結果可能溢位,其結果不準確 ,故不正確
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
public static int parseInt(String s, int radix)
throws NumberFormatException
{
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;//當值為負數是,更換邊界判斷
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) { //multmin = -214748364
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
bitCount (int)
返回該數值對應的二進位制中 1 的個數
public static int bitCount(int i) {
//5 0101 設低四位i為 b3*2^3+b2*2^2+b1*2^1+b0
//(i >>> 1) & 0x55555555:b3*2^2+b1*2^1
i = i - ((i >>> 1) & 0x55555555);//等於(b3+b2)*2^2+(b1+b0)
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);//b3+b2+b1+b0
i = (i + (i >>> 4)) & 0x0f0f0f0f;//b7+b6+..+b1+b0
i = i + (i >>> 8);//b15+b14+..+b1+b0
i = i + (i >>> 16);//b31+b30+..+b1+b0
return i & 0x3f;// int 32位 10_0000 6位故與11_1111(0x3f)與
}
compare()與compareUnsigned()
//正常比較 x>y 返回1 x==y 返回0 x<y 返回 -1
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
//負數>正數 -1>-2 2>1
public static int compareUnsigned(int x, int y) {
return compare(x + MIN_VALUE, y + MIN_VALUE);
}
decode()將字串解碼成Integer型別
支援帶符號的十 八(前導0) 十六(0x 0X #)進位制
public static Integer decode(String nm)
throws NumberFormatException
signum()返回符號位
public static int signum(int i) {
// HD, Section 2-7
//正 0 負:0 0 -1|1 0 0 = 1 0 -1
return (i >> 31) | (-i >>> 31);
}
divideUsigned(int int) 返回兩個數視為無符號整數後進行除法的到的商
Character
java中字元由utf16為變長表示,長度可能是2或4個位元組 java中的char是佔用兩個位元組,只不過有些字元需要兩個char來表示。
-
Character 的完整宣告和構造方法
class Character implements java.io.Serializable, Comparable<Character>
{
//1.已過時的構造方法
public Character(char value) {
this.value = value;
}
//文件建議:使用valueOf(char)代替建構函式 通常是更好的選擇,因為它可能產生明顯更好的空間和時間效能。
public static Character valueOf(char c) {
if (c <= 127) { // must cache
return CharacterCache.cache[(int)c];
}
return new Character(c);
}
....
}
-
codepoint 和 char
1.關於UTF-16的編碼的判斷
程式碼點: int整型表示任一Unicode字元,整型編號稱為程式碼點
BMP (Basic Multilingual Plane)字元 0x0000~0XFFFF 常用字符集 兩位元組表示
補增字符集 使用4位元組表示 前兩個位元組 稱為高代理項 0xD800~0XDFF HighSurrogate
後兩個位元組 稱為低代理項 0XDC00~0XDFF LowSurrogate
- bmp 一個字元算作一個程式碼點 ,表示補增字元 兩個字元 算作一個程式碼點
- 一個int型轉換成UTF-16編碼 可能是一個char型(BMP) 或者 兩個char型(補增字符集)
關於UTF-16編碼的判斷的方法:
3個關於程式碼點型別的判斷方法 isValidCodePoint()、isSupplementaryCodePoint()、isBmpCodePoint()
3個關於char的判斷是否為代理項的方法isSurrogate()、isHighSurrogate、isLowSurrogate() (surrogate 表示代理點)
1個關於整型字元編碼
isSupplementaryCodePoint(int codePoint) |
是否為補充程式碼點 |
|
isValidCodePoint(int codePoint) |
是否為有效程式碼點 | U + 0000到U + 10FFFF |
isBmpCodePoint(int codePoint) | 是否為Bmp程式碼點 | codePoint>>>16 ==0 (小於0xFFFF) |
isHighSurrogate(char ch) |
char是否為低代理項 |
|
isLowSurrogate(char ch) |
char是否為高代理項 |
|
isSurrogate(char ch) |
是否為低/高代理項 |
[0xD800 ,0xDfff] |
isSurrogatePair(char high, char low) |
是否high為高代理項 low為帶代理項 呼叫HighSurrogate和isLowSurrogate` |
|
public static int charCount(int codePoint) | 該程式碼點需要幾個char表示 大於0x10000需2個 否則需1個 |
1.按codepoint程式碼點處理char[ ]
{BMP,char[intdex]->int ; 補增,char[index],char[index+1]->int}
-
codePointAt()
-
兩種情況1.BMP 將一個char轉成int返回 2.補增字符集 兩個char 返回 tocodePoint()將高低代理項返回成int型代理點
//1和2 依靠codePointAtImpl實現其功能
public static int codePointAt(char[] a, int index);//1
public static int codePointAt(char[] a, int index, int limit) { //2
if (index >= limit || limit < 0 || limit > a.length) {
throw new IndexOutOfBoundsException();
}
return codePointAtImpl(a, index, limit);
public static int codePointAt(CharSequence seq, int index) { //3
char c1 = seq.charAt(index);
if (isHighSurrogate(c1) && ++index < seq.length()) {
char c2 = seq.charAt(index);
if (isLowSurrogate(c2)) {
return toCodePoint(c1, c2);
}
}
return c1;
}
// codePointAtImpl() 訪問修飾符default僅同一包中的類可訪問
static int codePointAtImpl(char[] a, int index, int limit) {
char c1 = a[index];
/*index自增
*對於補增字元需要兩個char表示,若c1為高代理項,則需要 a[index+1]是否是低代理項
*/ if (isHighSurrogate(c1) && ++index < limit) { //需判斷是否越界
char c2 = a[index];
if (isLowSurrogate(c2)) {
return toCodePoint(c1, c2);
}
}
return c1;
}
-
codePointBefore() {BMP,char[intdex-1]->int ; 補