Number類常用的方法
(一)、將 Number 對象轉(zhuǎn)換為xxx數(shù)據(jù)類型的值并返回。
##例子:
Integer x = 5;
System.out.println(x.byteValue());//返回byte原生數(shù)據(jù)類型
System.out.println(x.doubleValue());//返回double原生數(shù)據(jù)類型
System.out.println(x.floatValue());//返回float原生數(shù)據(jù)類型
System.out.println(x.longValue());//返回long原生數(shù)據(jù)類型
System.out.println(x.intValue());//返回int原生數(shù)據(jù)類型
System.out.println(x.shortValue());//返回short原生數(shù)據(jù)類型
(二)、compareTo()方法
(1).使用場景
##適用場景:
1.將 Number 對象與方法的參數(shù)進(jìn)行比較。
2.可用于比較 Byte, Long, Integer等。
3.該方法用于兩個相同數(shù)據(jù)類型的比較。
##不適用場景:
1.兩個不同類型的數(shù)據(jù)不能用此方法來比較。
(2).語法
public int compareTo( NumberSubClass referenceName )
##參數(shù)說明:
referenceName :可以是一個 Byte, Double, Integer, Float, Long 或 Short 類型的參數(shù)。
##返回值
1.如果指定的數(shù)與參數(shù)相等返回0。
2.如果指定的數(shù)小于參數(shù)返回 -1。
3.如果指定的數(shù)大于參數(shù)返回 1。
( 三)、equals()
使用場景:用于判斷 Number 對象與方法的參數(shù)進(jìn)是否相等。
###例子:
Integer x = 5;
Integer y = 10;
Integer z = 5;
Short a = 15;
System.out.println(x.equals(y));
System.out.println(x.equals(z));
System.out.println(x.equals(a));
(四)、valueOf()
(1).使用場景:
1.方法用于返回給定參數(shù)的原生 Number 對象值,參數(shù)可以是原生數(shù)據(jù)類型, String等。
2.該方法是靜態(tài)方法。該方法可以接收兩個參數(shù)一個是字符串,一個是基數(shù)。
(2).語法:
static Integer valueOf(int i)
static Integer valueOf(String s)
static Integer valueOf(String s, int radix)
##參數(shù)說明:
1.i -- Integer 對象的整數(shù)。
2.s -- Integer 對象的字符串。
3.radix --在解析字符串 s 時使用的基數(shù),用于指定使用的進(jìn)制數(shù)。
(3).返回值:
1.Integer valueOf(int i):返回一個表示指定的 int 值的 Integer 實(shí)例。
2.Integer valueOf(String s):返回保存指定的 String 的值的 Integer 對象。
3.Integer valueOf(String s, int radix): 返回一個 Integer 對象,該對象中保存了用第二個參數(shù)提供的基數(shù)進(jìn)行解析時從指定的 String 中提取的值。
(4).實(shí)例:
Integer a = Integer.valueOf(9);
Double b = Double.valueOf(5);
Float c = Float.valueOf("80");
Integer d = Integer.valueOf("444",16);
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
(五)、toString()
(1).語法:
String toString()
static String toString(int i) //i -- 要轉(zhuǎn)換的整數(shù)。
##返回值
toString(): 返回表示 Integer 值的 String 對象。
toString(int i): 返回表示指定 int 的 String 對象。
(2).實(shí)例:
Integer x = 5;
System.out.println(x.toString());
System.out.println(Integer.toString(12));
(六)、parseInt()
##將字符串參數(shù)作為有符號的十進(jìn)制整數(shù)進(jìn)行解析。
##語法
static int parseInt(String s)
static int parseInt(String s, int radix)
##參數(shù)
s -- 十進(jìn)制表示的字符串。
radix -- 指定的基數(shù)
##返回值
parseInt(String s): 返回用十進(jìn)制參數(shù)表示的整數(shù)值。
parseInt(int i): 使用指定基數(shù)的字符串參數(shù)表示的整數(shù) (基數(shù)可以是 10, 2, 8, 或 16 等進(jìn)制數(shù)) 。
##實(shí)例:
int x =Integer.parseInt("9");
double c = Double.parseDouble("5");
int b = Integer.parseInt("444",16);
System.out.println(x);
System.out.println(c);
System.out.println(b);