《JAVA300集》常用类-day8

目录

Java常用类

包装类

自动装箱和拆箱

String类

StringBuilder类

Data时间类

Canlendar类

Math类

File类

 使用递归遍历目录结构

枚举


Java常用类

包装类

Java中有包装类可以把基本的数据转化为对象,便于操作,如为了把基本数据类型存储到Object[]数组中等。

java.lang包里有八种包装类,分别和基本数据类型一一对应,命名就是首字母大写(除了char-Character和int-Integer)。

包装类的作用

基本数据类型、包装类对象、字符串之间提供相互之间的转化

public class TestWrappedClass {
    public static void main(String[] args) {
        // 基本数据类型转成包装类对象
        Integer a = new Integer(3);
        Integer b = Integer.valueOf(3); // 官方推荐写法

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

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

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

    }
}

自动装箱和拆箱

Java有自动装箱(autoboxing)和自动拆箱(autounboxing)功能。

自动装箱:基本类型的数据处于需要对象的环境中,会自动转为对象。装箱:转为对象类型。

自动拆箱:每当需要一个值的时候,对象会自动转成基本数据类型。拆箱:转为基本数据类型。

由于是自动的,所以在讲包装类中的上述代码不需要了,比如没有必要显式调用intValue()。这个功能是否实行是由编译器决定的。

Integer i = 100;//自动装箱

// 等价于下行的代码:

Integer i = Integer.valueOf(100);//调用的是valueOf(100),而不是new Integer(100)

Integer i = 100;

int j = i;//自动拆箱

// 等价于下行的代码:

int j = i.intValue();

注:包装类在自动装箱时为了提高效率,对于-128~127之间的值会进行缓存处理。超过范围后,对象之间不能再使用==进行数值的比较,而是使用equals方法。

// 【测试】超过-128-128范围,对象,不能再使用==进行数值的比较,而是使用equals方法

public class Test3 {
    public static void main(String[] args) {
        Integer in1 = -128;
        Integer in2 = -128;
        System.out.println(in1 == in2);//true 因为123在缓存范围内
        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));//true
    }
}

String类

String 类对象代表不可变的Unicode字符序列,String 类对象是不可变对象。 

使用string类的一个注意事项:编译器在遇到字符串常量拼接的时候,进行了优化,会在编译期间就完成了字符串的拼接。需要注意如下代码示例:

public class TestString2 {
    public static void main(String[] args) {
        //编译器做了优化,直接在编译的时候将字符串进行拼接
        String str1 = "hello" + " java"; //相当于str1 = "hello java";
        String str2 = "hello java";
        System.out.println(str1 == str2); //true
        String str3 = "hello";
        String str4 = " java";
        //编译的时候还不知道变量中存储的是什么,所以判断的时候会是false
        String str5 = str3 + str4;
        System.out.println(str2 == str5); //false
        System.out.println(str3.equals(str5)); //false
    }
}

 String类常用函数小概括:

      1. String类的下述方法能创建并返回一个新的String对象: concat()、 replace()、substring()、 toLowerCase()、 toUpperCase()、trim()。

      2. 提供查找功能的有关方法: endsWith()、 startsWith()、 indexOf()、lastIndexOf()。

      3. 提供比较功能的方法: equals()、equalsIgnoreCase()、compareTo()。

      4. 其它方法: charAt() 、length()。

StringBuilder类

StringBuilder类是为了补充String类不可变的特点,其对象是可变的。

string本身是不可改变的,它只能赋值一次,每一次内容发生改变,都会生成一个新的对象,这样大量操作字符的代码会占用特别多的空间。

StringBuilder类则不同,每次操作都是对自身对象进行操作,而不是生成新的对象,其所占空间会随着内容的增加而扩充

当程序中需要大量的对某个字符串进行操作时(如循环累加),应该考虑应用StringBuilder类处理该字符串,避免产生太多的临时对象;

而当程序中只是对某个字符串进行一次或几次操作时,采用string类即可。

(参考博客:https://www.cnblogs.com/mrxy/p/8057657.html

Data时间类

在标准Java类库中包含一个Date类。它的对象表示一个特定的瞬间,精确到毫秒。

import java.util.Date;

public class TimeClass {
    public static void main(String[] args) {
        Date date1 = new Date();
        System.out.println(date1);
        long i = date1.getTime();
        Date date2 = new Date(i - 1000);  // 单位毫秒
        System.out.println(date2);
    }
}

运行结果: (new Date()的值是当前时间)

DataFormat类

DataFormat类的作用: (1)把时间对象转化成指定格式的字符串。(2)把指定格式的字符串转化成时间对象。

其中,DateFormat是一个抽象类,一般使用它的的子类SimpleDateFormat类来实现。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDataFormat {
    public static void main(String[] args) throws ParseException {
        // new出SimpleDateFormat对象
        SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        SimpleDateFormat s2 = new SimpleDateFormat("yyyy-MM-dd");
        // 将时间对象转换成字符串
        String daytime1 = s1.format(new Date());
        String daytime2 = s2.format(new Date());
        System.out.println(daytime1);
        System.out.println(daytime2);
        System.out.println(new SimpleDateFormat("hh:mm:ss").format(new Date()));
        // 将符合指定格式的字符串转成成时间对象.字符串格式需要和指定格式一致。
        String time = "2020-12-15";
        Date date = s2.parse(time);
        System.out.println("date1: " + date);
        time = "2020-11-15 20:15:30";  // 之前指定过类型了
        date = s1.parse(time);
        System.out.println("date2: " + date);
    }
}

运行结果: (在转化为字符串时是12小时制,运行这段代码的时间是2020年12月15号21:17分)

这种 yyyy-MM等 格式化字符有很多,需要时可以再上网查阅。

注意Data类中的很多API已经被Calendar类中的方法取代了

Canlendar类

遇到日期处理,使用Canlendar类。

 Calendar 类是一个抽象类,为我们提供了关于日期计算的相关功能,比如:年、月、日、时、分、秒的展示和计算。

其中, GregorianCalendar 是 Calendar 的一个具体子类,提供了世界上大多数国家/地区使用的标准日历系统。

雷区:注意月份的表示,一月是0 == JANUARY,二月是1 等等

package Test;

import java.util.*;
public class TestCalendar {
    public static void main(String[] args) {
        // 得到相关日期元素
        GregorianCalendar calendar = new GregorianCalendar(2020, 11, 15, 21, 25, 50);
        int year = calendar.get(Calendar.YEAR);
        System.out.println(year);
        printCalendar(calendar);

        // 设置日期
        GregorianCalendar calendar2 = new GregorianCalendar();
        calendar2.set(Calendar.YEAR, 2999);
        calendar2.set(Calendar.MONTH, Calendar.FEBRUARY); // 月份数:0-11
        calendar2.set(Calendar.DATE, 3); // 日:Calendar.DATE和Calendar.DAY_OF_MONTH同义
        calendar2.set(Calendar.HOUR_OF_DAY, 10);
        calendar2.set(Calendar.MINUTE, 20);
        calendar2.set(Calendar.SECOND, 23);
        printCalendar(calendar2);

        // 日历对象和时间对象转化
        Date d = calendar2.getTime();
        GregorianCalendar calendar4 = new GregorianCalendar();
        calendar4.setTime(new Date());
        long g = System.currentTimeMillis();
    }
    static void printCalendar(Calendar calendar) {
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int date = calendar.get(Calendar.DAY_OF_WEEK) - 1; // 星期几
        String week = "" + ((date == 0) ? "日" : date);
        int hour = calendar.get(Calendar.HOUR);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        System.out.printf("%d年%d月%d日,星期%s %d:%d:%d\n", year, month, day,
                week, hour, minute, second);
    }
}

运行结果: 

Math类

java.lang.Math提供了一系列静态方法用于科学计算;其方法的参数和返回值类型一般为double型。

如果需要计算高等数学中的相关内容,可以使用apache commons下面的Math类库。

public class TestMath {
    public static void main(String[] args) {
        //取整相关操作
        System.out.println(Math.ceil(3.2));  //ceil(double a) 大于a的最小整数
        System.out.println(Math.floor(3.2)); //floor(double a) 小于a的最大整数
        System.out.println(Math.round(3.2)); //round 四舍五入
        System.out.println(Math.round(3.8));
        //绝对值、开方、a的b次幂等操作
        System.out.println(Math.abs(-45));
        System.out.println(Math.sqrt(64));  // sqrt 平方根
        System.out.println(Math.pow(5, 2));
        System.out.println(Math.pow(2, 5));
        //Math类中常用的常量
        System.out.println(Math.PI);
        System.out.println(Math.E);
        //随机数
        System.out.println(Math.random()); // [0,1)
    }
}

Random类,这个类是专门用来生成随机数的,并且Math.random()底层调用的就是Random的nextDouble()方法。 

import java.util.Random;
public class TestRandom {
    public static void main(String[] args) {
        Random rand = new Random();
        //随机生成[0,1)之间的double类型的数据
        System.out.println(rand.nextDouble());
        //随机生成int类型允许范围之内的整型数据
        System.out.println(rand.nextInt());
        //随机生成[0,1)之间的float类型的数据
        System.out.println(rand.nextFloat());
        //随机生成false或者true
        System.out.println(rand.nextBoolean());
        //随机生成[0,10)之间的int类型的数据
        System.out.print(rand.nextInt(10));
        //随机生成[20,30)之间的int类型的数据
        System.out.print(20 + rand.nextInt(10));
        //随机生成[20,30)之间的int类型的数据(此种方法计算较为复杂)
        System.out.print(20 + (int) (rand.nextDouble() * 10));
    }
}

File类

java.io.File类:代表文件和目录。 读取文件、生成文件、删除文件、修改文件的属性时经常会用到本类。

import java.io.File;
public class TestFile1 {
    public static void main(String[] args) throws Exception {
        System.out.println(System.getProperty("user.dir"));
        File f = new File("a.txt"); //相对路径:默认放到user.dir目录下面
        f.createNewFile(); //创建文件
        File f2 = new File("d:/b.txt"); //绝对路径
        f2.createNewFile();
    }
}

File类中的常用访问文件的属性的方法:

import java.io.File;
import java.util.Date;
public class TestFile2 {
    public static void main(String[] args) throws Exception {
        File f = new File("d:/b.txt");
        System.out.println("File是否存在:"+f.exists());
        System.out.println("File的大小:"+f.length());
    }
}

File类中的常用创建文件的属性的方法

import java.io.File;
public class TestFile3 {
    public static void main(String[] args) throws Exception {
        File f = new File("d:/c.txt");
        f.createNewFile(); // 会在d盘下面生成c.txt文件
        f.delete(); // 将该文件或目录从硬盘上删除
        File f2 = new File("d:/电影/华语/大陆");
        boolean flag = f2.mkdir(); //目录结构中有一个不存在,则不会创建整个目录树
        System.out.println(flag);//创建失败
    }
}

 使用递归遍历目录结构

package Test;

import java.io.File;

public class TestFileClass {
    public static void main(String[] args) {
        File f = new File("d:/Relax/电影");
        printFile(f, 0);
    }

    static void printFile(File file, int level) {
        //输出层次数,实现类似树状结构
        for (int i = 0; i < level; i++) {
            System.out.print("-");
        }

        //输出文件名
        System.out.println(file.getName());

        //如果file是目录,则获取子文件列表,并对每个子文件进行相同的操作
        if (file.isDirectory()) {
            File[] files = file.listFiles();  // 核心代码
            for (File temp : files) {
                //递归调用该方法:注意等+1
                printFile(temp, level + 1);
            }
        }
    }
}

运行结果: 

枚举

 当需要定义一组常量时,可以使用枚举类型。所有的枚举类型隐性地继承自 java.lang.Enum。他们默认都是public static final修饰的

enum  枚举名 {

      枚举体(常量列表)

}

enum Season {
    SPRING, SUMMER, AUTUMN, WINDER 
}

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值