您的位置:首页 > 编程语言 > Java开发

JAVA API系列----基本数据类型的对象包装类

2011-03-18 18:09 453 查看
·使用基本数据类型如int,char可以改善系统的性能,但是基本数据类型不具有对象的特性,不能满足某些特殊的需求,如需要方法需要传递的参数是Object类型,必须将基本类型转换为包装类如Integer,Character。

·将String对象转化为int类型方法:

1.通过将String类转化为Integer包装类,再调用包装类的intValue()方法将其转化为int型,如new Integer("50").intValue();

2.调用静态方法Integer.parseInt()方法或Integer.parseInt(String s, int radix) 方法,如Integer.parseInt("50");

parseInt(String s, int radix) 方法将s转换为radix指定的进制,如radix==8,则结果用8进制表示。
方法 parseInt(String s)与方法intValue()得到的是十进制的结果。

·String与StringBuffer运行效率比较:

String str = new String();
for (int i=0;i<w;i++){
/*先将str转换为StringBuffer类型,将‘*’追加到StringBuffer中,再调用toString方法转换为String对象,效率降低*/
str = str + '*';
}
StringBuffer str = new StringBuffer();
for (int i=0;i<w;i++){
/*运行效率比使用String类效率高*/
str = str.append('*');
}


Test Code:

public class TestInteger {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int height = Integer.parseInt(args[0]);        //将字符串arg[0]转换为整数
int width = Integer.parseInt(args[1]);
StringBuffer strBuffer = new StringBuffer();
for(int j=0;j<width;j++){
strBuffer = strBuffer.append('*');           //生成输出的字符串
}
for(int i=0;i<height;i++){
System.out.println(strBuffer.toString());	//打印字符串
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: