java常用类(1)

     一:基本数据类型的包装类

       java是面向对象的语言,但并不是“纯面向对象”的,如基本数据类型就不是对象。但我们在实际应用中将基本数据转化成对象,便于操作。如:将数据类型存储到Object[]数组或集合中的操作等等。

       为了解决不足,java在设计类时为每个基本数据类型设计了一个对应的类进行代表,这样八个和基本数据类型对应的统称为包装类(Wrapper Class)。

        包装类均位于java.long报包,八种包装类和基本数据类型的对应关系如下:

         

Integer的使用示例(其它类型的使用类似):

package cn.tanjianjie.test;
/**
*测试包装类
* Integer的使用
*/
public class TestWrapperClass {
public static void main(String[] args){
//基本数据类型转成包装类对像
Integer a=new Integer(3);//继承抽象类numbered类,numbered类包括所有的数据类型
Integer b=Integer.valueOf(30);//官方写法

//把包装类对像转成基本数据类型
int c=b.intValue();
double d=b.doubleValue();

//把字符串转成包装类对象
Integer e=new Integer("3333");
Integer f=Integer.parseInt("33333333");

//把包装类对象转成字符串
String str=f.toString();//""+f

//常见常量
System.out.println("int类型最大的整数");
}
}

       二:自动装箱和自动拆箱

       自动装箱和拆箱就是将基本数据类型和包装类之间进行自动的相互转换。

自动装箱:

        基本数据类型处于需要对象的环境中时,会自动转为“对象”。如通过自动装箱,不用通过Integer i=new Integer(5);这样的语句来实现基本数据类型转换成包装类的过程,而可以直接用Imteger i=5;这样的语句就能实现基本数据类型转换成包装类,因为JVM微我们执行Integer i=new Integer.valueOf(5)这样的操作,这就是java的自动装箱。

自动拆箱:

       每当需要一个值时,对象会自动转成基本数据类型,没必要去显示调用intValue()、doubleValue()等转型方法。如Integer i=5;int j=i;这样的过程就是自动拆箱。

总之:自动装箱过程是通过调用包装类的valueOf()方法实现的,而自动拆箱过程是通过调用包装类的xxxValue()方法实现的[xxx]代表对应的基本数据类型,如intValue(),doubleValue()等。示例:  

package cn.tanjianjie.test;
/**
*测试自动装箱、自动拆箱
*/
public class TestAutoBox{
public static void main(String[] args){
Integer a=234;//自动装箱
int b=a;//自动拆箱

//缓存[-128,127]之间的数字
Integer in1=-128;
Integer in2=-128;
System.out.println(in1==in2);//true因为-128在缓冲范围内
System.out.println(in1.equals(in2));//true

Integer in3=1234;
Integer in4=1234;
System.out.println(in3==in4);//false因为1234不在缓冲范围内
System.out.println(in3.equals(in4));//false
}
}

运行结果:

String类:

          String类对象代表不可变的Unicode字符序列,所以称String对象为“不可变对象”(因为其核心数组有final修饰)。对象的内部的成员变量的值无法再改变。字符串进行比较时用equals,不使用==。

StringBuilder与StringBuffer区别(可变字符序列):

StringBuilder线程还能不安全,效率高。

StringBuffer线程安全,效率低(常用)。

示例:

package cn.tanjianjie.test;
/**
* 测试StringBuilder可变字符序列
*/
public class TestSttringBuilder {
public static void main(String[] args){
StringBuilder sb=new StringBuilder("abcd");
System.out.println(Integer.toHexString(sb.hashCode()));//获取地址
System.out.println(sb);

sb.setCharAt(2,'e');
System.out.println(Integer.toHexString(sb.hashCode()));//获取地址
System.out.println(sb);
}
}
运行结果:

StringBuilder与StringBuffer的常用方法:

倒序:Object.reverse();

改变特定位置的字符:Object.setChat(x,String);x代表位置,Stirng代表字符用单引号。

插入:Object.insert(x,String);

删除:Object.delect(x,String);

更多方法见java帮助文档。

注意可变序列与不可变序列的陷阱:

如:

这样的程序浪费空间与时间。

应用如下所示进行替换:

 

猜你喜欢

转载自www.cnblogs.com/Gsan/p/10322375.html