包装类的基础知识
Java在设计类时为每个基本数据类型设计了一个对应的类进行代表,这样八个和基本数据类型对应的类统称为包装类(Wrapper Class)。
包装类提供了基本数据类型,包装类,字符串三者之间的转换
自动装箱,拆箱
Integer a = 234;自动//对于编译器是Integer a = Integer.valueOf(234);——装箱
int b = a;//对于编译器是int b = a.intValue();——拆箱
包装类的缓存问题
缓存处理的原理为:如果数据在-128~127这个区间,那么在类加载时就已经为该区间的每个数值创建了对象,并将这256个对象存放到一个名为cache的数组中。每当自动装箱过程发生时(或者手动调用valueOf()时),就会先判断数据是否在该区间,如果在则直接获取数组中对应的包装类对象的引用,如果不在该区间,则会通过new调用包装类的构造方法来创建对象。
String类
String是不可变对象
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];//可以看到我们定义的数据是放到这个final修饰的value数组里
此外在字符串的拼接过程中
//编译器做了优化,直接在编译的时候将字符串进行拼接
String str1 = "hello" + " java";//相当于str1 = "hello java";
String str2 = "hello java";
System.out.println(str1 == str2);//true
Date类
Date d = new Date(2000);
System.out.println(d.getTime());
DateFormat与SimpleDateFormat
//把时间对象转化为指定格式字符串
DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
String string = df.format(new Date(4000000));
System.out.println(string);
//把字符串转化成时间
DateFormat dFormat2 = new SimpleDateFormat("yyyy年MM月dd日 hh时mm分ss秒");
Date date = dFormat2.parse("2015年10月16日 19时35分26秒");
System.out.println(date);
//测试其他格式
DateFormat df3 = new SimpleDateFormat("W");
String string2 = df3.format(date);
System.out.println(string2);
Canlendar类
//获取日期相关元素
Calendar c = new GregorianCalendar(2020,10,9,22,10,50);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
int weekday = c.get(Calendar.DAY_OF_WEEK);
System.out.println(year+" "+month+" "+day+" "+weekday);
//设置日期相关元素
Calendar c2 = new GregorianCalendar();
c2.set(Calendar.YEAR, 2020);
System.out.println(c2.get(Calendar.YEAR));
//日期的计算
Calendar c3 = new GregorianCalendar();
c3.add(Calendar.YEAR, 10);
System.out.println(c3.get(Calendar.YEAR));
//日历对象和时间对象转化
Date date = c3.getTime();//日期类转时间
Calendar c4 = new GregorianCalendar();
c4.setTime(date);//时间类转日期
System.out.println(c4);
File类
File f = new File("d://a.txt");//f2ile f2 =new f2ile("d:\a.txt");这两种写法等价
ps注意路径用\,目录用/
//文件的创建和删除
File f2 = new File("gg.txt");
f2.createNewFile();
f2.delete();
//midir与midirs的区别
File testFile = new File("d:/1/2/3");
boolean flag1 = testFile.mkdir();//目录结构有一个不存在,则不会创建整个目录树
boolean flag2 = testFile.mkdirs();//目录结构有不存在的也没关系,创建整个目录树
System.out.println(testFile.getAbsolutePath());
递归遍历目录结构和树状展现
public class TestPrintFileTree {
public static void main(String[] args) {
File testFile = new File("d:\\1\\2");
print(testFile,1);
}
public static void print(File file,int level) {
for (int i = 0; i < level; i++) {
System.out.print("-");
}
System.out.println(file.getName());
if(file.isDirectory()) {
File[] files=file.listFiles();
for(File temp:files) {//这里特别注意这是增强型for循环,类似于for-each
print(temp,level+1);
}
}
}
}
枚举类
在有必要定义一组常量的时候用枚举
enum Season {
SPRING, SUMMER, AUTUMN, WINDER
}
枚举实质上还是类!而每个被枚举的成员实质就是一个枚举类型的实例(对象)