之前我們已經詳細解讀了Integer的基本屬性,toString
方法,toUnsignedString0
方法,parseInt
方法,valueOf
方法,接下來就再來看一下看其他幾個比較常用也比較簡單的方法。
compareTo和compare
這裏看一下兩個方法:
public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
Integer類實現了Comparable接口,compareTo
方法是接口方法的實現,具體就是調用了compare
方法。
compare
方法代碼簡單明瞭,x小於y則返回-1,相等則返回0,否則返回1。
hashCode
public int hashCode() {
return Integer.hashCode(value);
}
public static int hashCode(int value) {
return value;
}
這個方法就是直接返回對應的int值。
equals
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
先判斷是不是Integer類型再比較值是不是相等。
decode
public static Integer decode(String nm) throws NumberFormatException {
int radix = 10;
int index = 0;
boolean negative = false;
Integer result;
if (nm.length() == 0)
throw new NumberFormatException("Zero length string");
char firstChar = nm.charAt(0);
// Handle sign, if present
if (firstChar == '-') {
negative = true;
index++;
} else if (firstChar == '+')
index++;
// Handle radix specifier, if present
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
index += 2;
radix = 16;
}
else if (nm.startsWith("#", index)) {
index ++;
radix = 16;
}
else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
index ++;
radix = 8;
}
if (nm.startsWith("-", index) || nm.startsWith("+", index))
throw new NumberFormatException("Sign character in wrong position");
try {
result = Integer.valueOf(nm.substring(index), radix);
result = negative ? Integer.valueOf(-result.intValue()) : result;
} catch (NumberFormatException e) {
// If number is Integer.MIN_VALUE, we'll end up here. The next line
// handles this case, and causes any genuine format error to be
// rethrown.
String constant = negative ? ("-" + nm.substring(index))
: nm.substring(index);
result = Integer.valueOf(constant, radix);
}
return result;
}
decode方法主要作用是把帶前綴的字符串轉成Integer型,
0x
或0X
或#
前綴的解析爲十六進制進行轉換,0
前綴的解析爲八進制進行轉換,沒有前綴的則解析爲十進制進行轉換。
比如Integer.decode("15")
的結果爲15,Integer.decode("0x15")
和Integer.decode("#15")
結果都爲21,Integer.decode("015")
結果爲13。
byteValue, shortValue, intValue, longValue, floatValue, doubleValue
public byte byteValue() {
return (byte)value;
}
public short shortValue() {
return (short)value;
}
public int intValue() {
return value;
}
public long longValue() {
return (long)value;
}
public float floatValue() {
return (float)value;
}
public double doubleValue() {
return (double)value;
}
這幾個方法也是特別簡單,其實就是轉換成對應的類型進行返回。
還有幾個方法,如bitCount
,highestOneBit
,lowestOneBit
,numberOfLeadingZeros
,numberOfTrailingZeros
,reverse
,reverseBytes
等,這些方法的實現都是大量的移位操作、位與、位或等位運算,非常複雜,而且JDK基於高效的考慮,很多邏輯進行了轉換,爲了速度放棄了可讀性,導致很難讀懂,加之這幾個方法也不太常用,這裏就先不一一去解讀。