封装类的由来:
为了将基本类型以对象行使存在,java对八个基本类型提供了引用类型,这八个引用类型称为基本类型的“包装类”。
八个基本类型对应的封装类:
int ---> Integer
char ---> Character
byte ---> Byte
float ---> Float
double ---> Double
short ---> Short
long ---> Long
boolean ---> Boolean
封装类的作用:
1.用于集合存储
2.String转基本数据类型间相互转换:
基本数据类型 -->String通过重载方法valueOf()即可
String转基本数据类型通过基本类型对应的封装类即可
1 //int->String
2 String s =String.valueOf(a);3 String ss =Integer.toString(a);4
5 //String->int
6 int i =Integer.parseInt(b);7
8 //1.Integer转换成int的方法,即Integer.intValue();
9 Integer ii = new Integer(10);10 int k =ii.intValue();11
12 //2.int转换成Integer
13 int c = 10;14 Integer it = newInteger(c);15
16 //3. String转换成Integer
17 String str = "10";18 Integer d =Integer.valueOf(str);19
20 //4.Integer转换成String
21 Integer e = new Integer(10);22 String stre =e.toString();23 //或者写成
24 String strwe = Integer.toString(e);
↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
上面只是举了int&String的例子,其他的都差不多,Integer替换成Double啦~ Character啦~ 用法都差不多的
哦对了 项目中 String和Date的互相转换也是十分常见的,常用的方法有SimpleDateFormat,ThreadSafeSimpleDateFormat
但是推荐用ThreadSafeDateFormat,为什么呢?因为SimpleDateFormat不仅线程不安全,而且用这个方法会创建成吨的实例对象,占用大量的内存和 jvm空间,总之少用就对了。
下面展示下两种方法的实例:
SimpleDateFormat():
1 public classDateUtil {2
3 public static String formatDate(Date date)throwsParseException{4 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");5 returnsdf.format(date);6 }7
8 public static Date parse(String strDate) throwsParseException{9 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");10 returnsdf.parse(strDate);11 }12 }
ThreadSafeSimpleDateFormat(): 此处是Date转字符串
1 //首先在共通类写个format方法,假设这个类叫做AA
2 private static Pattern patternDate = Pattern.compile("[yMdHms]*");3
4 publicString formatDate(SimpleDateFormat sdfDate, Date date) {5 String result = "";6 if (date != null) {7 result =sdfDate.format(date);8 } else{9 Matcher matcher =patternDate.matcher(sdfDate.toPattern());10 result = matcher.replaceAll("-");11 }12 returnresult;13 }14
15
16 //然后,调用就完事了
17 AA aa = newAA()18 aa.formatDate(new ThreadSafeSimpleDateFormat("HHmm"), xxx.getDate());
其实SimpleDateFormat也有避免创建大量实例的写法,但是线程不安全,我就不写了(主要是懒)。
ps:同一个方法如果出现多个return,只以第一个为准,后面的都不管。
好了就这么多了,不过话说回来 我的随笔真是越来越短小了 ,最近鼻炎又找上我了,项目也忙起来了,回到家整个人都没了力气
哎其实都是借口,明晚一定要写一篇,突然想起来我的java连数据库那部分约等于不会,明晚研究一下,并把心得记录下来 。
下期见! 一给窝哩giaogiao !