java 数据封装_java封装数据类型——Integer

今天来学习整型 int 的封装数据类型,Integer。

1. 定义

首先来看看定义。可以看到,Integer 继承 Number 抽象类,实现了 Comparable 接口。Number 类是常用数字类型类的公共父类,它规定了其子类(通常就是数字类)必须提供将其值转换成 int、long、float、double、byte、short 类型数据的能力。实现 Comparable 接口自然是为了比较大小。另外,Integer 类型也是最终类,不可被继承(事实上,常用数据类型的封装类都是 final 类)。

6f3d747ba9cd729d85daab0ab73388bc.png

2. 属性

2.1. 表示 int 数据类型上下界值的字段:MIN_VALUE = -231 ,MAX_VALUE = 231-1 ;

2.2. Integer 类型类对象的引用:TYPE;

187cbf6dbf546d22eabdd39a5a3ab8bf.png

3. 构造方法

Integer 提供两个构造方法,分别接收一个 int 数据类型和一个 string 类型(不是整数会报错)。

public Integer(intvalue) {this.value =value;

}publicInteger(String s) throws NumberFormatException {this.value = parseInt(s, 10);

}

4. 普通方法

static int

返回指定的int值的二进制补码二进制表示中的 int数。

byte

返回此值 Integer为 byte的基本收缩转换后。

static int

compare(int x, int y)

比较两个 int数字值。

int

compareTo(Integer anotherInteger)

数字比较两个 Integer对象。

static int

比较两个 int值,以数值方式将值视为无符号。

将 String解码成 Integer 。

static int

divideUnsigned(int dividend, int divisor)

返回将第一个参数除以秒的无符号商,其中每个参数和结果被解释为无符号值。

double

返回此值 Integer为 double一个宽元转换后。

boolean

将此对象与指定的对象进行比较。

float

返回此值 Integer为 float一个宽元转换后。

确定具有指定名称的系统属性的整数值。

确定具有指定名称的系统属性的整数值。

返回具有指定名称的系统属性的整数值。

int

返回这个 Integer的哈希码。

static int

hashCode(int value)

返回值为int的哈希码; 兼容Integer.hashCode() 。

static int

返回一个 int值与至多一个单个1位,在最高阶(“最左侧”)的位置在指定的一个位 int值。

int

将 Integer的值作为 int 。

long

返回此值 Integer为 long一个宽元转换后。

static int

在指定的 int值中,以最低位(最右边)为1位返回一个最多为单个1位的 int值。

static int

max(int a, int b)

返回两个 int的较大值,就像调用 Math.max一样 。

static int

min(int a, int b)

返回两个 int的较小值,就像调用 Math.min一样 。

static int

返回的最高阶的(“最左边的”)中所指定的二进制补码表示的一个位前述零个比特的数量 int值。

static int

返回零位以下最低阶(“最右边的”)的数量在指定的二进制补码表示的一个位 int值。

static int

将字符串参数解析为带符号的十进制整数。

static int

parseInt(String s, int radix)

将字符串参数解析为第二个参数指定的基数中的有符号整数。

static int

static int

将字符串参数解析为第二个参数指定的基数中的无符号整数。

static int

remainderUnsigned(int dividend, int divisor)

返回无符号余数,将第一个参数除以秒,其中每个参数和结果被解释为无符号值。

static int

reverse(int i)

返回由指定的二进制补码表示反转位的顺序而获得的值 int值。

static int

返回反转指定的二进制补码表示的字节顺序而获得的值 int值。

static int

rotateLeft(int i, int distance)

返回通过旋转指定的二的补码的二进制表示而得到的值 int由位指定数目的左值。

static int

rotateRight(int i, int distance)

返回通过旋转指定的二的补码的二进制表示而得到的值 int右移位的指定数值。

short

返回此值 Integer为 short的基本收缩转换后。

static int

signum(int i)

返回指定的 int值的 int函数。

static int

sum(int a, int b)

根据+运算符将两个整数相加。

static String

在基数2中返回整数参数的字符串表示形式为无符号整数。

static String

返回整数参数的字符串表示形式,作为16位中的无符号整数。

static String

在基数8中返回整数参数的字符串表示形式为无符号整数。

返回 String表示此对象 Integer的价值。

static String

返回一个 String指定整数的 String对象。

static String

toString(int i, int radix)

返回由第二个参数指定的基数中的第一个参数的字符串表示形式。

static long

参数给转换 long由无符号转换。

static String

将参数的字符串表示形式返回为无符号十进制值。

static String

toUnsignedString(int i, int radix)

以第二个参数指定的基数中的无符号整数值返回第一个参数的字符串表示形式。

valueOf(int i)

返回一个 Integer指定的 int值的 Integer实例。

返回一个 Integer对象,保存指定的值为 String 。

valueOf(String s, int radix)

返回一个 Integer对象,保存从指定的String中 String的值,当用第二个参数给出的基数进行解析时。

4.1. byteValue()、shortValue()、intValue()、longValue()、floatValue()、doubleValue(),这些是继承自 Number 类的方法,返回当前 Integer 对象对应 int 值对应的各种数据类型值(通过强制类型转换,强转到低精度时可能丢失数据)

4.2. compareTo(Integer) 方法

该方法接收一个被比较的 Integer 类对象,并与之比较大小,遵循 Comparable 接口的常规约定:若当前值等于参数值,返回 0;若当前值小于参数值,返回 -1;若当前值大于参数值,返回 1;

public intcompareTo(Integer anotherInteger) {return compare(this.value, anotherInteger.value);

}/**

* Compares two {@code int} values numerically.

* The value returned is identical to what would be returned by:

*

 
 

* Integer.valueOf(x).compareTo(Integer.valueOf(y))

*

*

* @param x the first {@code int} to compare

* @param y the second {@code int} to compare

* @return the value {@code 0} if {@code x == y};

* a value less than {@code 0} if {@code x < y}; and

* a value greater than {@code 0} if {@code x > y}

* @since 1.7*/

public static int compare(int x, inty) {return (x < y) ? -1 : ((x == y) ? 0 : 1);

}

4.3. decode(String),解码方法,将参数字符串解码得到 Integer,该方法自动识别正负符号和进制符号(如:0x、0、# 等),如 -0xa1 = -161,默认是 正数 和 十进制

public staticInteger 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);

}returnresult;

}

可以看到,decode 方法首先对正负号和进制符号进行识别判断,最后将剩下的纯数值部分和得到的进制数值调用静态工厂方法 valueOf(string, int) 构造 Integer 对象。

4.4. valueOf 静态方法

Integer 类支持整型和字符串型参数的工厂方法,其中字符串型的工厂方法支持指定进制,并且会先使用 parseInt 方法解析出原始 int 数值,再通过 valueOf (int) 方法构造 Integer 对象。parseInt 方法就是遍历字符串并使用进制值加权累加计算了。最值得注意的是 int 参数的 valueOf 方法,它体现了 Integer 类的缓存策略,后面单独讲。

public static Integer valueOf(String s, intradix) throws NumberFormatException {returnInteger.valueOf(parseInt(s,radix));

}public staticInteger valueOf(String s) throws NumberFormatException {return Integer.valueOf(parseInt(s, 10));

}public static Integer valueOf(inti) {if (i >= IntegerCache.low && i <=IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return newInteger(i);

}

4.4. getInteger 方法

该方法返回 string 参数指定的系统属性值。支持指定默认值(通过第二个参数),若该属性不存在或者不是 int 类型,则返回默认值

public staticInteger getInteger(String nm) {return getInteger(nm, null);

}public static Integer getInteger(String nm, intval) {

Integer result= getInteger(nm, null);return (result == null) ?Integer.valueOf(val) : result;

}public staticInteger getInteger(String nm, Integer val) {

String v= null;try{

v=System.getProperty(nm);

}catch (IllegalArgumentException |NullPointerException e) {

}if (v != null) {try{returnInteger.decode(v);

}catch(NumberFormatException e) {

}

}returnval;

}

4.5. hashCode() 方法

Integer 的 hashCode() 值就是它所保存的 int 型值。

/**

* Returns a hash code for this {@code Integer}.

*

* @return a hash code value for this object, equal to the

* primitive {@code int} value represented by this

* {@code Integer} object.*/@Overridepublic inthashCode() {returnInteger.hashCode(value);

}/**

* Returns a hash code for a {@code int} value; compatible with

* {@code Integer.hashCode()}.

*

* @param value the value to hash

* @since 1.8

*

* @return a hash code value for a {@code int} value.*/

public static int hashCode(intvalue) {returnvalue;

}

4.6. equals(Integer) 方法

Integer 的 equals 方法比较的就是保存的 int 型值是否相等。很显然,hashCode 和 equals 方法遵循散列的常规约定。

publicboolean equals(Object obj) {if(obj instanceof Integer) {return value ==((Integer)obj).intValue();

}return false;

}

5. Integer 的缓存机制

前面学习 Boolean 类保存两个对 true 和 false 值对象的静态引用,使用 valueOf 构造对象时会始终返回其一。Integer 类也同样使用了这种缓存机制。上文中提到了静态工厂方法 valueOf(int) 使用了缓存策略,代码中使用了 IntegerCache 类,那么我们就来看看该类源码,这是 Integer 类的一个内部类,专门用于处理 Integer 缓存机制:

cef8069da1085508d218eb9a9f599767.png

可以看出,该类是私有内部类,开发者不可改变和初始化。该类通过静态代码块在类加载的时候,循环创建 Integer 缓存对象,并创建索引表进行引用,需要时使用索引表快速获取。缓存值范围最小是 -128,最大默认是 127(可以使用虚拟机参数指定,虚拟机默认无该参数)。缓存对象值和所在索引表位置偏移量即是 127。

再回头看看 valueOf(int) 方法:当需要构造的 Integer 对象值在缓存范围之内时,就从索引表查找缓存对象直接返回,否则构造新的对象返回。所以大家在开发中需要构建 Integer 对象时,推荐使用静态工厂方法,少用 new 以节省开支。

27d4f26a2e42db76071d509bc40efb65.png

6. 总结

6.1. Integer 是对 int 型的封装数据类型,能表示的范围是  -231 ~ 231-1 的所有整数;

6.2. Integer 的 hashCode 值就是它所保存的 int 型值;

6.3. Integer 提供了很多实用方法:min、max、sum、转换成二/八/十六进制的字符串表示等;

6.4. Integer 使用了对象缓存机制,默认范围是  -128 ~ 127 ,推荐使用静态工厂方法 valueOf 获取对象实例,而不是 new,因为 valueOf 使用缓存,而 new 一定会创建新的对象分配新的内存空间;

【附】

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值