标签:code java String int 数据类型 wrapper str Integer
Wrapper包装类
基本数据类型由于不是类,不能够使用java类库提供的大量方法,所以在设计上,我们为每一个基本数据类型都对应一个类,同时数据存储的范围不变,此时基本数据类型就具备了类的特点。
基本数据类型 | 包装类 |
---|---|
byte | Byte |
char | Character |
short | Short |
int | Integer |
long | Long |
double | Double |
float | Float |
boolean | Boolean |
继承关系
Character
Boolean
Byte,Short,Integer,Long,Double,Float
装箱
基本数据类型包装成包装类的实例
Integer i = 1;
实现方式
/**
* The value of the {@code Integer}.
*
* @serial
*/
private final int value;
/**
* Constructs a newly allocated {@code Integer} object that
* represents the specified {@code int} value.
*
* @param value the value to be represented by the
* {@code Integer} object.
*/
public Integer(int value) {
this.value = value;
}
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
解析过程:先执行valueOf方法,当条件满足的时候,会直接返回InterCache中的值,否则,会new
一个Integer
对象
拆箱
获取包装类对象中包装的基本数据类型变量
调用包装类的.xxxValue()方法
int i = Integer.intValue();
字符串和基本数据类型的相互转换
-
基本数据类型转换成字符串
-
通过空字符+基本数据类型
String str = "" + 10;
-
使用
String
类的静态方法valueOf
String str = String.valueOf(10);
-
先将基本类型装修对象,然后调用对象的
toString
方法Integer i = new Integer(10); String str = i.toString();
-
-
字符串转换成基本数据类型
-
调用各自的包装类的静态方法
String str = "100"; int i = Integer.parseInt(str);
-
直接
new
包装类int i = new Integer(str);
-
包装类和字符串相互转换
-
包装类转换成字符串
-
通过空字符+基本数据类型
String str = "" + i;
-
使用
String
类的静态方法valueOf
String str = String.valueOf(i);
-
调用对象的
toString
方法String str = i.toString();
-
-
字符串转换成包装类
-
通过new 包装类
Integer i = new Integer(str);
-
通过包装类的
valueOf
方法Integer i = Integer.valueOf(str);
-
整体图解
标签:code,java,String,int,数据类型,wrapper,str,Integer 来源: https://www.cnblogs.com/ywjcqq/p/16281933.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。