JAVA之包装类Integer详解

来源:互联网 发布:网络有关的电影 编辑:程序博客网 时间:2024/06/05 03:26
包装类Integer


1.构造方法:
①Integer(int x)以int型作为参数创建Integer对象;
Integer number = new Integer(7);
②Integer(String str)以String型变量作为参数创建Integer对象;
Integer number = new Integer("123");
注意:要用数值型String变量作为参数;


2.常用方法:
方法 返回类型 功能说明
①byteValue(): byte返回Integer对象的byte类型值
②intValue(): int返回Integer对象的int类型值
③shortValue(): short返回Integer对象的short类型值
④compareTo(Integer anotherInteger): int在数值上比较两个Integer对象,如果值相等返回0,如果调用对象小于antherInteger对象,返回负值,否则返回正值
⑤equals(Integer anotherInteger): boolean在数值上比较两个Integer对象,如果相等返回true,否则返回false
⑥toString(): String使用形式有以下三种eg:①Integer a = Integer.valueOf(5);String str = Integer.toString(a);
             ②Integer a = Integer.valueOf(5);String str = a.toString();
     ③String str = Integer.toString(123);
⑦valueOf(String str | int i): Integer 返回保存指定的String值或者int值的Integer对象
⑧parseInt(String str) int返回包含在由str指定的字符串中的数字的等价的整数值

eg:

package Number;public class IntFunction{public static void main (String []args){Integer a1 = Integer.valueOf(45); Integer a2 = Integer.valueOf("45");byte b1 = a1.byteValue();short b2 = a1.shortValue();int b3 = a1.intValue();System.out.println("byte:" + b1 + ",short:" + b2 + ",int:" + b3);int b4 = a1.compareTo(a2);boolean bool = a1.equals(a2);System.out.println("compareTo:" + b4 + ",equals: " + bool);String str1 = Integer.toString(234);String str2 = a2.toString();String str3 = Integer.toString(a2);System.out.println("str1:" + str1 + ",str2:" + str2 + ",str3:" + str3);int b5 = Integer.parseInt("678");System.out.println("b5:" + b5);}}/*运行结果:byte:45,short:45,int:45compareTo:0,equals: truestr1:234,str2:45,str3:45b5:678*/