文章目录
1 包装类基本知识
java是面向对象的语言,但并不是“纯面向对象的”,因为我们常用的基本数据类型就不是对象,但是在实际应用中需要将基本数据转化为对象,以便于操作。如将基本数据类型存储到Object[ ]数组或集合中的操作等等
为了解决这个不足,Java在设计时为每个基本数据类型设计了一个对应的类型代表,这样8个和基本数据类型对应的类统称为包装类,包装类均位于java.lang包中
使用Integer创建基本数据类型对象及内存分析:
2 包装类Integer的使用
包装类提供了基本数据类型和包装类对象和字符串的互相转化
package cn.coisini.testclass;
/**
* 测试包装类
* Integer类的使用,其它包装类类似
* @author coisini1999
*
*/
public class TestWrappedClass {
public static void main(String[] args) {
//基本数据类型转成包装类对象
Integer a = new Integer(3);
Integer b = Integer.valueOf(30);
//把包装类对象转成基本数据类型
int c = b.intValue();
double d = b.doubleValue();
//把字符串转成包装类对象
Integer e = new Integer("9999");
Integer f = Integer.parseInt("9998");
//把包装类对象转成字符串
String str = f.toString();
//常见的常量
System.out.println("int类型最大整数:" + Integer.MAX_VALUE);
}
}
3 包装类的自动装箱和拆箱
自动装箱:基本数据类型处于需要对象的环境中时,会自动转为 对象
自动拆箱:每当需要一个值时,对象会自动转成基本数据类型,没必要显式的调用intValue()等方法
自动装箱和自动拆箱实际上是由编译器帮助完成的
package cn.coisini.testclass;
/**
* 测试自动装箱和拆箱
* @author coisini1999
*
*/
public class TestAutoBox {
public static void main(String[] args) {
//自动装箱
Integer a = 234; //编译器实际执行:Integer a = Integer.valueOf(234);
//自动拆箱
int b = a; //编译器实际执行:int b = a.intValue();
}
}
自动拆箱时如果不注意对象是否为空可能出现空指针
4 Integer的缓存
使用Integer创建对象前,Integer已经创建好了从[-128,127]之间的对象存放在了缓冲区中,待使用时直接从中取出,不需再创建,不在[-128,127]范围内的才会在堆中创建对象
5 String类要点
String类对象代表不可变的Unicode字符序列,因此可以将String对象称为“不可变对象”,即对象内部的成员变量的值无法更改
从源码中可以看到存放字符串的数组是final修饰的,不可更改
在String上所有的修改本质上是生成新的字符串
在比较字符串是否相等时要使用equals(),==是用来判断字符串是否是同一个对象
6 StringBuilder和StringBuffer
StringBuilder/StringBuffer不同于String,其中存储字符串的数组并无final修饰,可以用StringBuilder/Buffer去修改字符串
7 StringBuilder/StringBuffer的一些方法
package cn.coisini.testclass;
/**
* 测试StringBuilder,StringBuffer可变字符串序列
* @author coisini1999
*
*/
public class TestStringBuilder2 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 26; i++) {
char temp = (char)('a'+i);
sb.append(temp);
}
System.out.println(sb);
System.out.println("######");
sb.reverse();
System.out.println(sb);
System.out.println("######");
sb.setCharAt(3, '$');
System.out.println(sb);
System.out.println("######");
sb.insert(0, '我');
System.out.println(sb);
//链式调用,核心是:该方法调用了return this
sb.insert(6, '你').insert(10, '他').insert(16, '她');
System.out.println(sb);
System.out.println("######");
sb.delete(20, 24);
System.out.println(sb);
System.out.println("######");
}
}
8 可变字符序列和不可变字符序列使用陷阱
循环累加可变字符串时使用StringBuilder,不能循环累加,在服务器程序中使用循环累加,产生过多对象,会降低服务器效率