Java基础学习Day10--常用类
今天公司又是没什么业务
今天学习了java中的一些常用类
一、包装类:
1.什么是包装类
所谓包装类,就是能够直接将简单类型的变量表示为一个类,在执行变量类型的相互转换时,我们会大量使用这些包装类。
2.拆箱与装箱
既然有了基本数据类型和包装类,就必然存在它们之间的转换,如:
public static void main(String[] args) {
Integer a = 0;
for(int i = 0; i < 100; i++){
a += i;
}
}
将基本数据类型转化为对应类型的包装类的过程叫“装箱”;将包装类转为对应类型的基本数据类型的过程叫“拆箱”
在上面中给变量a赋值的时候就发生了装箱,而在参与计算的过程中就发生了拆箱,但是我们好像什么都没做,这句是自动拆装箱
下面我们再给一个例子:
装箱:
int num = 25;
Integer i = Integer.valueOf(num);
Integer i = 25;
拆箱:
Integer i = new Integer(10);
//unboxing
int num = i;
Float f = new Float(56.78);
float fNum = f;
3.自动拆箱与自动装箱
Java为了简便拆箱与装箱的操作,提供了自动拆装箱的功能,这极大地方便了程序员们。那么到底是如何实现的呢?。这个特性是在java5中引入的
下面的例子就是一个自动拆箱与装箱的过程,通过反编译工具我们得到,
public static void main(String[] args) {
Integer a = Integer.valueOf(0);
for (int i = 0; i < 100; i++) {
a = Integer.valueOf(a.intValue() + i);
}
}
我们不难发现,主要调用了两个方法,Integer.intValue() 和 Integer.valueOf( int i) 方法
查看Integer源码,我们找到了对应代码:
/**
* Returns the value of this {@code Integer} as an {@code int}.
* 返回一个 Integer 的int 值
*/
public int intValue() {
return value;
}
/**
* Returns an {@code Integer} instance representing the specified {@code int} value.
* 返回一个代表特定int 值的 Integer 对象
* If a new {@code Integer} instance is not required, this method should generally be used in preference to the constructor {@link #Integer(int)},
* 如果不需要一个新的Integer 实例,则通常应优先使用此方法而不是构造函数
* 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.
* 此方法将始终缓存-128到127(含)范围内的值,并可能缓存此范围之外的其他值。
* @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);
}
很明显,我们我们得出,Java帮你隐藏了内部细节。拆箱的过程就是通过Integer 实体调用intValue()方法;装箱的过程就是调用了 Integer.valueOf(int i) 方法,帮你直接new了一个Integer对象
4.什么时候进行自动拆装箱?
其实很简单(就是在需要对象的时候就装箱需要基本类型的时候就拆箱)
(1)添加到集合中时,进行自动装箱
(2)涉及到运算的时候,“加,减,乘, 除” 以及 “比较 equals,compareTo”,进行自动拆箱
5.包装类型与switch
public static void main(String[] args) {
int iVal = 7;
switch(iVal) {
ca