0
点赞
收藏
分享

微信扫一扫

7、StringBuffer与日期相关类


StringBuffer类

1、  String类的内容一旦声明就不可以改变,如果改变其实是换了一个String对象,如果要改变字符串内容怎么办,可以使用StringBuffer类

2、  因为String类改变是通过改变String对象来实现内容的变化,而StringBuffer则是直接改变对象内容,所以从性能上考虑应尽量多使用StringBuffer来处理字符串

对比以下两种方式大量修改字符串,看看性能的差异有多大

import java.util.Date;

publicclass hello{
publicstaticvoid main(String args[]){
Date t1 =new Date();

//String字符串修改一万次
String x ="a";
for(int i=0; i<10000; i++){
x +="a";
}

Date t2 =new Date();
System.out.println("String loop 10000 times, costmillisecond : "+(t2.getTime()-t1.getTime()));

//StringBuffer字符串修改一万次
StringBuffer y =new StringBuffer();
for(int i=0; i<10000; i++){
y.append("a");
}

Date t3 =new Date();
System.out.println("StringBuffer loop 10000 times, costmillisecond : "+(t3.getTime()-t2.getTime()));
}
}

 

 

时间相关类

1、  Date,日期类,需要引用包,import java.util.Date;

2、  Calendar,日历类,引用包,import java.util.Calendar;

3、  DateFormat,日期格式化类,引用包,import java.text.DateFormat;

4、  SimpleDateFormat,简单日期格式化类,引用包,import java.text.SimpleDateFormat;

5、  一般只使用Date与SimpleDateFormat类即可,如下

import java.util.Date;
import java.text.SimpleDateFormat;

publicclass hello{
publicstaticvoid main(String args[])throws Exception{
//声明时间格式
SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-ddHH:mm:ss SSS");

//将时间格式化为日期字符串
Date d =new Date();
System.out.println(sdf.format(d));
//将字符串转换为时间对象,再将时间对象格式化为字符串
d = sdf.parse("2017-08-18 08:08:08 888");
System.out.println(sdf.format(d));
}
}

 

举报

相关推荐

0 条评论