九 Java常用类

课程视频 : https://www.bilibili.com/video/BV1vt4y197nY

Object类

  • 超类、基类,所有类的直接或间接父类,位于继承树的最顶层
  • 任何类,如没有书写extends显式继承某个类,都默认直接继承Object类,否则为间接继承
  • Object类中所定义的方法,是所有对象都具备的方法
  • Object类型可以存储任何对象
    • 作为参数,可接受任何对象
    • 作为返回值,可返回任何对象

getClass()方法

  • public final Class<?> getClass(){}
  • 返回引用中存储的实际对象类型
  • 应用:通常用于判断两个引用中实际存储对象类型是否一致

代码示例

public class Demo01_Object {
    public static void main(String[] args) {
        Student student1 = new Student();
        Student student2 = new Student();
        System.out.println(student1.getClass());
        if(student1.getClass()==student2.getClass())
        {
            System.out.println("两者类型相同");
        }
        else
        {
            System.out.println("两者类型不同");
        }
        
    }
}
class Student{
    String name;
    int age;
}

运行结果

image-20220223192400859

hashCode()

  • public int hashCode(){}
  • 返回该对象的哈希码值
  • 哈希值根据对象的地址字符串数字使用hash算法计算出来的int类型的值
  • 一般情况下相同对象返回相同哈希码,一般用来判断两个对象是否是同一个

代码示例

System.out.println("###############");
System.out.println("hashCode");
System.out.println(student1.hashCode());
System.out.println(student2.hashCode());
Student student3 = student2;
System.out.println(student3.hashCode());//3和2的地址一样

运行结果

image-20220224165018854

toString()

  • public final Class<?> getClass(){}

  • 返回该对象的字符串表示(表现形式)

  • 可以根据程序需求覆盖该方法,如:展示对象各个属性值

代码示例

class Teacher{
    String name;
    int age;

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
System.out.println("##############");
System.out.println(student1.toString());
Teacher teacher = new Teacher();
System.out.println(teacher.toString());

运行结果

image-20220223192942864

😄查看toString方法,后面的数字其实是对象的哈希值hashcode

equals()方法

  • public boolean equals(Object obj){}
  • 默认实现为(this == obj), 比较两个对象地址是否相同
  • 可进行覆盖,比较两个对象的内容是否相同

代码示例

System.out.println("###############");
System.out.println("equals");
System.out.println(student1.equals(student2));
System.out.println(student2.equals(student3));

运行结果

image-20220224165906645

重写equals方法

// 重写 改变其比较内容
/*
步骤  1. 比较两个应用是否指向同一个对象
     2. 判断obj是否为null
     3. 判断两个引用只想的实际对象类型是否一致
     4. 强制类型转换
     5. 依次比较各个属性值是否相同
*/
@Override
public boolean equals(Object obj) {
    // 1.
    if(this == obj){
        return true;
    }
    // 2.
    if(obj == null){
        return false;
    }
    // 3.
    // if(this.getClass() == obj.getClass()){
    //
    // }
    // instanceof 判断对象是否是某种类型
    if(obj instanceof Teacher){
        // 4.强制类型转换
        Teacher s = (Teacher) obj;
        // 5. 比较属性
       	if(this.name.equals(s.getName()) && this.age == s.getAge()){
            return true;
        }
    }
    return false;
}

测试

Teacher teacher1 = new Teacher("XXX",18);
Teacher teacher2 = new Teacher("XXX",18);
System.out.println(teacher1.equals(teacher2));//true

finalize()

  • 当对象被判定为垃圾对象时,由JVM自动调用此方法,用以标记垃圾对象,进入回收队列
  • 垃圾对象:没有有效引用指向此对象时,为垃圾对象
  • 垃圾回收:由gc销毁垃圾对象,释放数据存储空间
  • 自动回收机制:JVM的内存耗尽,一次性回收所有垃圾对象
  • 手动回收机制:使用System.gc();通知JVM执行垃圾回收

重写finalize()方法

@Override
protected void finalize() throws Throwable {
    System.out.println(name+"被回收了");
}

测试

ystem.out.println("###############");
System.out.println("finalize()");
Student student4 = new Student("AAA",21);
new Student("BBB",21);
new Student("CCC",21);
new Student("DDD",21);
new Student("EEE",21);
new Student("FFF",21);
System.gc();
System.out.println("垃圾回收:");

运行结果

image-20220224172120301

包装类

  • 基本数据类型所对应的引用数据类型

  • Object 可统一所有数据,包装类的默认值是null

    基本数据类型包装类型
    byteByte
    shortShort
    intInteger
    longLong
    floatFloat
    doubleDouble
    booleanBoolean
    charCharacter

类型转换与装箱、拆箱

  • 装箱:把基本类型转换为引用类型
  • 拆箱:把引用类型转换为基本类型
  • 8种包装类提供不用类型间的转换方式
    • Number父类中提供的6个共性方法
    • parseXXX( )静态方法 String转换为XXX类型
    • XXX.valueOf(yyy)静态方法 yyy转换为XXX
public class Demo02_PackagingClass {
    public static void main(String[] args) {
        // 装箱, 基本类型 → 引用类型
        // 基本类型
        int num1 = 18;
        // 使用Integer类创建对象
        Integer integer1 = new Integer(num1);
        Integer integer2 = Integer.valueOf(num1);
        System.out.println("装箱");
        System.out.println(integer1);//18
        System.out.println(integer2);//18

        // 拆箱, 引用类型 → 基本类型
        Integer integer3 = new Integer(100);
        int num2 = integer3.intValue();
        System.out.println("拆箱");
        System.out.println(num2);//100

        // 上述为jdk1.5之前方法,之后提供了自动装箱拆箱
        int age = 30;
        // 自动装箱
        Integer integer4 = age;
        System.out.println("自动装箱");
        System.out.println(integer4);//30
        // 自动拆箱
        int age2 = integer4;
        System.out.println("自动拆箱");
        System.out.println(age2);//30

        // 基本类型和字符串之间转换
        System.out.println("---------基本类型和字符串之间转换-----------");
        // 1. 基本类型转成字符串
        int n1 = 15;
        // 1.1 使用+号
        String s1 = n1 + "";
        // 1.2 使用Integer中的toString()方法
        String s2 = Integer.toString(n1);
        String s3 = Integer.toString(n1,16); //第二个参数radix为进制要求
        String s4 = Integer.toHexString(n1);
        System.out.println(s1);//15
        System.out.println(s2);//15
        System.out.println(s3);//f
        System.out.println(s4);//f

        // 2. 字符串转成基本类型
        String str = "150";
        // 使用Integer.parseXXX();
        int n2 = Integer.parseInt(str);
        System.out.println(n2);//150

        // boolean 字符串形式转成基本类型,"true" ---> true 非“true"的任何 ———> false
        String str2 = "true";
        String str3 = "parse";
        boolean b1 = Boolean.parseBoolean(str2);
        boolean b2 = Boolean.parseBoolean(str3);
        System.out.println(b1);//true
        System.out.println(b2);//false
    }
}

整数缓冲区

  • Java预先创建了256个常用的整数包装类型对象
  • 在实际应用当中,对已创建的对象进行复用
//Integer包装类的valueOf源码,low=-128 high=127
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
public class Demo03_IntegerBuffer {
    public static void main(String[] args) {
        // 面试题
        Integer integer1 = new Integer(100);
        Integer integer2 = new Integer(100);
        System.out.println(integer1 == integer2); // false

        Integer integer3 = new Integer(100);// 自动装箱
        // 相当于调用 Integer.valueOf(100);
        Integer integer4 = new Integer(100);
        System.out.println(integer3 == integer4); // true

        Integer integer5 = new Integer(200);// 自动装箱
        Integer integer6 = new Integer(200);
        System.out.println(integer5 == integer6); // false

        // 查看上方Valueof源码,因为缓存区数组 [-128, 127] 在这之内对象复用,地址一样
    }
}

String类

  • 字符串是常量,创建之后不可改变
  • 字符串字面值存储在字符串池中,可以共享
  • 字符串创建两种方式:
    • String s = "Hello";产生一个对象,字符串池中存储
    • String s = new String("Hello"); 产生两个对象,堆、池各一个

不可变性

字符串是常量,创建之后不可改变

⭐️这里的内存分析中,字符串池在方法区中,但是不同版本的jdk,字符串池的位置不唯一

String name = "hello";//"hello"常量存储在字符串池中
name = "zhangsan";//将"张三"赋值给name变量,给字符串赋值时,并没有修改数据,而是重新开辟一个空间

image-20220225115340962

String name2 = "zhangsan";
System.out.println(name==name2);//true

image-20220225115709306

new创建String对象

String s = new String("Hello"); 产生两个对象,堆、池各一个

String str = new String("java");
String str2 = new String("java");
System.out.println(str==str2);//false
System.out.println(str.equals(str2));//true

image-20220225120508996

常用方法

  1. length(); 返回字符串长度
  2. charAt(int index); 返回某个位置的字符
  3. contains(String str); 判断是否包含某个字符串
  4. toCharArray(); 返回字符串对应数组
  5. indexOf(); 返回子字符串首次出现的位置
  6. lastIndexOf(); 返回字符串最后一次出现的位置
  7. trim(); //去掉字符串前后空格
  8. toUpperCase(); toLowerCase(); 转换大小写
  9. endsWith(str); startsWith(str); 判断是否以str 结尾、开头
  10. replace(char old, char new); 用新的字符或字符串替换旧的字符或字符串
  11. split(); 对字符串拆分
//常用方法
System.out.println("--------字符串常用方法1~3---------");
// 1. length(); 返回字符串长度
// 2. charAt(int index); 返回某个位置的字符
// 3. contains(String str); 判断是否包含某个字符串

String content = "java是最好的语言,java真香";
System.out.println(content.length()); // 17
System.out.println(content.charAt(content.length() - 1)); // 香
System.out.println(content.contains("java")); // true

// 4. toCharArray(); 返回字符串对应数组
// 5. indexOf(); 返回子字符串首次出现的位置
// 6. lastIndexOf(); 返回字符串最后一次出现的位置
System.out.println("--------字符串常用方法4~6---------");
System.out.println(Arrays.toString(content.toCharArray()));//[j, a, v, a, 是, 最, 好, 的, 语, 言, ,, j, a, v, a, 真, 香]
System.out.println(content.indexOf("java")); // 0
System.out.println(content.indexOf("java", 4)); // 从索引4开始找 返回11
System.out.println(content.lastIndexOf("java")); // 11

// 7. trim(); //去掉字符串前后空格
// 8. toUpperCase(); toLowerCase(); 转换大小写
// 9. endsWith(str); startsWith(str);  判断是否以str 结尾、开头
System.out.println("--------字符串常用方法7~9---------");
String ct = " hello world ";
System.out.println(ct.trim()); //hello world
System.out.println(ct.toUpperCase()); // HELLO WORLD
System.out.println(ct.toLowerCase()); // hello world
System.out.println(ct.endsWith("world")); //false
System.out.println(ct.startsWith(" ")); //true


// 10. replace(char old, char new); 用新的字符或字符串替换旧的字符或字符串
// 11. split(); 对字符串拆分
System.out.println("--------字符串常用方法10~11---------");
System.out.println(content.replace("java", "C++")); //C++是最好的语言,C++真香
String say = "java is the best language。。。java no.1";
String[] arr = say.split(" "); // "[ ,]+" 表示空格 逗号切分 +号表示切分可以多个 比如多个空格
System.out.println(arr.length); // 5
System.out.println(Arrays.toString(arr));//[java, is, the, best, language。。。java, no.1]
String[] arr1 = say.split("[ 。]");//用空格或句号分隔
System.out.println(Arrays.toString(arr1));//[java, is, the, best, language, , , java, no.1]中间是空
String[] arr2 = say.split("[ 。]+");//连续多个空格或句号
System.out.println(Arrays.toString(arr2));//[java, is, the, best, language, java, no.1]

// 补充两个equals/compareTo();比较大小
System.out.println("--------字符串常用方法(补充)---------");
String s1 = "hello";
String s2 = "HELLO";
System.out.println(s1.equalsIgnoreCase(s2));// 忽略大小写比较true

// compareTo(); 两字符不同时顺序依次比较字符字典序的ascii码
// 字符相同时比较长度 返回差值
String s3 = "abc";//a:97
String s4 = "xyz";//x:120
System.out.println(s3.compareTo(s4));//-23
String s5 = "abc";//a:97
String s6 = "aaaaaa";
System.out.println(s5.compareTo(s6));//1 ,顺序依次比较
String s7 = "abc";//a:97
String s8 = "abcdef";
System.out.println(s7.compareTo(s8));//-3 ,相同时比较长度

String类练习题

题目要求

  1. 已知String str = “this is a text”;
  2. 将str中的单词单独获取
  3. 将str中的text替换成practice
  4. 在text前面插入一个easy
  5. 将每个单词的首字母改为大写
String str ="this is a text";
String[] words = str.split(" ");
System.out.println(Arrays.toString(words));

String strReplace = str.replace("text", "practice");
System.out.println(strReplace);

String strInsert = str.replace("text", "easy text");
System.out.println(strInsert);

for (int i = 0; i < words.length; i++) {
    char first = words[i].charAt(0);
    char upperFirst = Character.toUpperCase(first);
    String news = upperFirst + words[i].substring(1);
    System.out.print(news+" ");
}

可变字符串

  • StringBuffer : 可变长字符串,运行效率慢、线程安全
  • StringBuilder : 可边长字符串,运行快、线程不安全

比String效率高节省内存

常用方法

public static void main(String[] args) {
    StringBuffer sb = new StringBuffer();
    // StringBuffer 和 StringBuilder 用法一致
    // 1. append(); 追加
    sb.append("java 世界第一");
    System.out.println(sb);//jdk1.8默认调用toString
    System.out.println(sb.toString());//java 世界第一
    // 2. insert(); 添加、插入
    sb.insert(0, "最前面");
    System.out.println(sb);//最前面java 世界第一
    // 3.replace(); 替换
    sb.replace(0, 1, "hello"); // 左闭右开
    System.out.println(sb.toString());//hello前面java 世界第一
    // 4. delete(); 删除
    sb.delete(0, 5); // 左闭右开
    System.out.println(sb);//前面java 世界第一
    // 5. 清空
    sb.delete(0, sb.length());
    System.out.println(sb.length());//0
}

与String效率比较

public static void main(String[] args) {
    String str = "";
    long start = System.currentTimeMillis();
    for (int i = 0; i < 99999; i++) {
        str = str + " ";
    }
    long end = System.currentTimeMillis();
    System.out.println("String耗时:"+(end-start));
    StringBuilder sb = new StringBuilder();
    start = System.currentTimeMillis();
    for (int i = 0; i < 99999; i++) {
        sb.append(" ");
    }
    end = System.currentTimeMillis();
    System.out.println("StringBuilder耗时:"+(end-start));
}

运行结果

image-20220225145146252

BigDecimal

  • 位置 java.math 包中
  • 作用 精确计算浮点数
  • 创建方式 BigDecimal bd = new BigDecimal("1.0");
double d1 = 1.0;
double d2 = 0.9;
System.out.println(d1-d2);//0.09999999999999998

//注意使用字符串的参数
BigDecimal bigDecimal1 = new BigDecimal("1.0");
BigDecimal bigDecimal2 = new BigDecimal("0.9");

//减法
BigDecimal result1 = bigDecimal1.subtract(bigDecimal2);
System.out.println(result1);//0.1

//加法
BigDecimal result2 = bigDecimal1.add(bigDecimal2);
System.out.println(result2);//1.9

//乘法
BigDecimal result3 = bigDecimal1.multiply(bigDecimal2);
System.out.println(result3);//0.90

//除法 (1.4-0.5)/0.9
BigDecimal result4 = new BigDecimal("1.4")
        .subtract(new BigDecimal("0.5"))
        .divide(new BigDecimal("0.9"));
System.out.println(result4);//1

//注意如果除不尽会报错
//BigDecimal result5 = new BigDecimal("10").divide(new BigDecimal("3"));//ArithmeticException
BigDecimal result6 = new BigDecimal("10").divide(new BigDecimal("3"),2,BigDecimal.ROUND_HALF_UP);//保留两位小数,四舍五入
System.out.println(result6);//3.33

Date类

  • Date表示特定的瞬间,精确到毫秒。Date类中的大部分方法都已经被Calendar类中的方法所取代
  • 时间单位:1s = 1,000ms = 1,000,000 μs = 1,000,000,000 = ns
//1创建Date对象
Date date1 = new Date();
System.out.println(date1.toString());//Fri Feb 25 15:13:50 CST 2022
System.out.println(date1.toLocaleString());//Fri Feb 25 15:13:50 CST 2022
// 创建昨天的
Date date2 = new Date(date1.getTime() - (60*60*24*1000));//一天的毫秒数
System.out.println(date2.toLocaleString());

// 2 方法after before
boolean b1 = date1.after(date2);
System.out.println(b1); //true
boolean b2 = date1.before(date2);
System.out.println(b2); //false

// 比较compareTo();
int d = date1.compareTo(date1);
System.out.println(d); // 多的为1 少的为 -1

// 比较是否相等 equals()
boolean b3 = date1.equals(date2);
System.out.println(b3); // false

Calendar类

  • Calendar提供了获取或设置各种日历字段的方法
  • 构造方法 protected Calendar(); 由于是protected 所以无法直接创建
  • 其他方法
方法名说明
static Calendar getInstance()使用默认时区和区域获取日历
void set(int year, int month, int date, int hourofday, int minute, int second)设置日历的年、月、日、时、分、秒
int get(int field)返回给定日历字段的值。字段比如年、月、日
void setTime(Date date)用给定的date设置此日历时间
Date getTime()返回一个date表示此日历的时间
void add(int field, int amount)按照日历的规则,给指定字段添加或减少时间量
long getTimeInMilles()毫秒为单位返回该日历的时间值
  // 1. 创建 Calendar 对象
  Calendar calendar = Calendar.getInstance();
  sout(calendar.getTime().toLocaleString());
  // 2. 获取时间信息
  // 获取年
  int year = calendar.get(Calendar.YEAR);
  // 获取月 从 0 - 11
  int month = calendar.get(Calendar.MONTH);
  // 日
  int month = calendar.get(Calendar.DAY_OF_MONTH);
  // 小时
  int hour = calendar.get(Calendar.HOUR_OF_DAY);
  // 分钟
  int minute = calendar.get(Calendar.MINUTE);
  // 秒
  int second = calendar.get(Calendar.SECOND);
  // 3. 修改时间
  Calendar calendar2 = Calendar.getInstance();
  calendar2.set(Calendar.DAY_OF_MONTH, x);
  // 4. add修改时间
  calendar2.add(Calendar.HOUR, x); // x为正就加 负就减
  // 5. 补充方法
  int max = calendar2.getActualMaximum(Calendar.DAY_OF_MONTH);// 月数最大天数
  int min = calendar2.getActualMinimum(Calendar.DAY_OF_MONTH);

SimpleDateFormat类

  • SimpleDateFormat是一个以与语言环境有关的方式来格式化和解析日期的具体类
  • 进行格式化(日期→文本)、解析(文本→日期)
  • 常用的时间模式字母
字母日期或时间示例
y2019
08年中月份08
d月中天数10
H一天中小时(0-23)22
m分钟16
s59
S毫秒356
public static void main(String[] args) throws ParseException {
    System.out.println("-----格式化-----");
    //1.创建SimpleDateFormat对象
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //2.创建Date对象
    Date date = new Date();
    //3.格式化date
    System.out.println(sdf.format(date));

    System.out.println("-----解析-----");
    Date date2 = sdf.parse("2022-02-25 16:03:50");//可能存在无法解析的异常,格式不符合 ParseException
    System.out.println(date2);
}

System类

主要用于获取系统的属性数据和其他操作,构造方法私有的

方法名说明
static void arraycopy(…)复制数组
static long currentTimeMillis();获取当前系统时间,返回毫秒值
static void gc();建议jvm赶快启动垃圾回收期器回收垃圾
static void exit(int status);退出jvm 如果参数是0表示正常退出jvm 非0表示异常退出
public static void main(String[] args) {
        //arraycopy 复制
        //src-原数组 srcPos-从哪个位置开始复制0 dest-目标数组 destPos-目标数组的位置 length-复制的长度
        int[] arr = {1, 2, 3, 4, 5};
        int[] dest = new int[5];
        System.arraycopy(arr,0,dest,0,arr.length);
        System.out.println(Arrays.toString(dest));//[1, 2, 3, 4, 5]

        int[] dest2 = Arrays.copyOf(arr,arr.length);
        System.out.println(Arrays.toString(dest2));//[1, 2, 3, 4, 5]

        //2.获取毫秒数
        System.out.println(System.currentTimeMillis());//1970.1.1到现在的毫秒数,常用来计时

        //3.System.gc();告诉垃圾回收期回收
        new Student("学生1",1);
        System.gc();

        //4.退出jvm
        System.exit(0);//后面的代码不会执行
        System.out.println("程序结束");
    }
) {
        //arraycopy 复制
        //src-原数组 srcPos-从哪个位置开始复制0 dest-目标数组 destPos-目标数组的位置 length-复制的长度
        int[] arr = {1, 2, 3, 4, 5};
        int[] dest = new int[5];
        System.arraycopy(arr,0,dest,0,arr.length);
        System.out.println(Arrays.toString(dest));//[1, 2, 3, 4, 5]

        int[] dest2 = Arrays.copyOf(arr,arr.length);
        System.out.println(Arrays.toString(dest2));//[1, 2, 3, 4, 5]

        //2.获取毫秒数
        System.out.println(System.currentTimeMillis());//1970.1.1到现在的毫秒数,常用来计时

        //3.System.gc();告诉垃圾回收期回收
        new Student("学生1",1);
        System.gc();

        //4.退出jvm
        System.exit(0);//后面的代码不会执行
        System.out.println("程序结束");
    }

Math类

算数计算:

  • Math.sqrt() : 计算算术平方根
  • Math.cbrt() : 计算立方根
  • Math.pow(a, b) : 计算a的b次方
  • Math.max( , ) : 计算最大值
  • Math.min( , ) : 计算最小值
  • Math.abs() : 取绝对值
System.out.println(Math.sqrt(16)); //4.0
System.out.println(Math.cbrt(8)); // 2.0
System.out.println(Math.pow(3, 2));//9.0
System.out.println(Math.max(2.3, 4.5));// 4.5
System.out.println(Math.min(2.3, 4.5));// 2.3
System.out.println(Math.abs(-10.4)); //10.4
System.out.println(Math.abs(10.1)); //10.1

进位:

Math.ceil(): 天花板的意思,就是逢余进一,返回double值
Math.floor() : 地板的意思,就是逢余舍一,返回double值
Math.rint(): 四舍五入,返回double值。注意.5的时候会取偶数
Math.round(): 四舍五入,float时返回int值,double时返回long值

// ceil天花板的意思,就是逢余进一 
System.out.println(Math.ceil(-10.1)); // -10.0
System.out.println(Math.ceil(10.7)); // 11.0
System.out.println(Math.ceil(-0.7)); // -0.0
System.out.println(Math.ceil(0.0)); // 0.0
System.out.println(Math.ceil(-0.0)); // -0.0
System.out.println(Math.ceil(-1.7)); // -1.0
System.out.println("-------------------");

// floor地板的意思,就是逢余舍一
System.out.println(Math.floor(-10.1)); // -11.0
System.out.println(Math.floor(10.7)); // 10.0
System.out.println(Math.floor(-0.7)); // -1.0
System.out.println(Math.floor(0.0)); // 0.0
System.out.println(Math.floor(-0.0)); // -0.0
System.out.println("-------------------");

//rint 四舍五入,返回double值 注意.5的时候会取偶数 异常的尴尬=。= 
System.out.println(Math.rint(10.1)); // 10.0
System.out.println(Math.rint(10.7)); // 11.0
System.out.println(Math.rint(11.5)); // 12.0
System.out.println(Math.rint(10.5)); // 10.0
System.out.println(Math.rint(10.51)); // 11.0
System.out.println(Math.rint(-10.5)); // -10.0
System.out.println(Math.rint(-11.5)); // -12.0
System.out.println(Math.rint(-10.51)); // -11.0
System.out.println(Math.rint(-10.6)); // -11.0
System.out.println(Math.rint(-10.2)); // -10.0
System.out.println("-------------------");

//round 四舍五入,float时返回int值,double时返回long值 
System.out.println(Math.round(10)); // 10
System.out.println(Math.round(10.1)); // 10
System.out.println(Math.round(10.7)); // 11
System.out.println(Math.round(10.5)); // 11
System.out.println(Math.round(10.51)); // 11
System.out.println(Math.round(-10.5)); // -10
System.out.println(Math.round(-10.51)); // -11
System.out.println(Math.round(-10.6)); // -11
System.out.println(Math.round(-10.2)); // -10

注意:参数要是float或者double。

随机数:

随机数产生有两种方式:

  • java.lang.Math.Random下的random方法,Math.random()只能产生 double 类型的 0~1 的随机数。
  • java.util.Random,Random 类提供了丰富的随机数生成方法,可以产生 boolean、int、long、float、byte 数组以及 double 类型的随机数,这是它与 random() 方法最大的不同之处。
    • 构造方法有两种:
    • Random():该构造方法使用一个和当前系统时间对应的数字作为种子数,然后使用这个种子数构造 Random 对象。
    • Random(long seed):使用单个 long 类型的参数创建一个新的随机数生成器。
  • ⭐️伪随机数,都是根据seed进行计算所得。
方法说明
boolean nextBoolean()生成一个随机的 boolean 值,生成 true 和 false 的值概率相等
double nextDouble()生成一个随机的 double 值,数值介于 [0,1.0),含 0 而不包含 1.0
int nextlnt()生成一个随机的 int 值,该值介于 int 的区间,也就是 -231~231-1。如果需要生成指定区间的 int 值,则需要进行一定的数学变换
int nextlnt(int n)生成一个随机的 int 值,该值介于 [0,n),包含 0 而不包含 n。如果想生成指定区间的 int 值,也需要进行一定的数学变换
void setSeed(long seed)重新设置 Random 对象中的种子数。设置完种子数以后的 Random 对象 和相同种子数使用 new 关键字创建出的 Random 对象相同
long nextLong()返回一个随机长整型数字
boolean nextBoolean()返回一个随机布尔型值
float nextFloat()返回一个随机浮点型数字
double nextDouble()返回一个随机双精度值
System.out.println("------随机数-----");

System.out.println("Math.random方法生成随机数");
System.out.println("生成的[0,1.0)区间的小数是"+Math.random());

System.out.println("Random类生成随机数");
Random r = new Random();
double d1 = r.nextDouble(); // 生成[0,1.0)区间的小数
double d2 = r.nextDouble() * 7; // 生成[0,7.0)区间的小数
int i1 = r.nextInt(10); // 生成[0,10)区间的整数
int i2 = r.nextInt(18) - 3; // 生成[-3,15)区间的整数
long l1 = r.nextLong(); // 生成一个随机长整型值
boolean b1 = r.nextBoolean(); // 生成一个随机布尔型值
float f1 = r.nextFloat(); // 生成一个随机浮点型值
System.out.println("生成的[0,1.0)区间的小数是:" + d1);
System.out.println("生成的[0,7.0)区间的小数是:" + d2);
System.out.println("生成的[0,10)区间的整数是:" + i1);
System.out.println("生成的[-3,15)区间的整数是:" + i2);
System.out.println("生成一个随机长整型值:" + l1);
System.out.println("生成一个随机布尔型值:" + b1);
System.out.println("生成一个随机浮点型值:" + f1);
System.out.print("下期七星彩开奖号码预测:");
for (int i = 1; i < 8; i++) {
    int num = r.nextInt(10); // 生成[0,9]区间的整数
    System.out.print(num);
}
System.out.println();

System.out.println("伪随机数证明");
Random random = new Random(100);
System.out.println(random.nextDouble());//0.7220096548596434
Random random1 = new Random(100);
System.out.println(random1.nextDouble());//0.7220096548596434

UUID

UUID 是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的。通常平台会提供生成的API。按照开放软件基金会(OSF)制定的标准计算,用到了以太网卡地址、纳秒级时间、芯片ID码和许多可能的数字。

而标准的UUID格式为:xxxxxxxx-xxxx-xxxx-xxxxxx-xxxxxxxxxx (8-4-4-4-12),其中每个 x 是 0-9 或 a-f 范围内的一个十六进制的数字。

System.out.println("唯一标识符UUID");
UUID uuid = UUID.fromString("46400000-8cc0-11bd-b43e-10d46e4ef14d");
UUID random_uuid = uuid.randomUUID();
System.out.println("uuid: " + uuid.toString() );//通过String变量构造对象访问
System.out.println("uuid.randomUUID(): " + random_uuid);//通过对象访问
System.out.println("UUID.randomUUID().toString():" + UUID.randomUUID().toString());//通过类名访问

运行结果

image-20220228134823872

File类(操作文件)

构造方法

通过给定的父抽象路径名和子路径名字符串创建一个新的File实例。

File(File parent, String child);

通过将给定路径名字符串转换成抽象路径名来创建一个新 File 实例。

File(String pathname);

根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例。

File(String parent, String child) 

通过将给定的 file: URI 转换成一个抽象路径名来创建一个新的 File 实例。

File(URI uri) 

相对路径表示方法

.表示当前目录,相对路径。
代表上一层目录,相对路径。
…/…/上一层目录的上一层目录,相对路径。
/根目录,绝对路径。
D:/New folder/物理路径,绝对路径。

⭐️注意包和文件夹的区别,package是包的意思,不是文件夹路径

1.创建

目录分割符:在Windows机器上的目录分隔符是\,在Linux机器上的目录分隔符是/

注意:在Windows上面\与/都可以作为目录分隔符。而且,如果写/的时候,只需要写1个正斜杠即可,而写\的时候,需要写2个反斜杠(转义字符)。

1.创建文件:

注意:需要进行异常处理。

createNewFile();//成功返回true

2.创建文件夹:

mkdir()     创建文件夹,如果父级路径不存在,则文件夹创建失败
mkdirs()    创建文件夹,如果父级路径不存在,则自动创建父级路径,再创建子级路径

3.renameTo(File dest):重命名文件或文件夹。文件路径不同时,相当于文件的剪切+重命名,剪切的时候不能操作非空文件夹。移动/重命名成功返回true,失败返回false。

当目标文件路径有重名文件或文件夹,重命名失败

System.out.println("-----createNewFile-------");
File file1 = new File("./基础语法/src/com/textFile/1.txt");
try {
    file1.createNewFile();
    System.out.println("创建文件成功");
} catch (IOException e) {
    e.printStackTrace();
    System.out.println("创建文件失败");
}

System.out.println("------mkdir()------");
File file2 = new File("./基础语法/src/com/textFile/folder1");
if(file2.mkdir()){
    System.out.println("父级路径存在,创建文件夹成功");
}
else {
    System.out.println("父级路径存在,创建文件夹失败");
}
File file3 = new File("./基础语法/src/com/textFile/folder2/folder2.2");
if(file3.mkdir()){
    System.out.println("父级路径不存在,创建文件夹成功");
}
else {
    System.out.println("父级路径不存在,创建文件夹失败");
}

System.out.println("------mkdirs()------");
File file4 = new File("./基础语法/src/com/textFile/folder2/folder2.2");
if(file4.mkdirs()){
    System.out.println("父级路径不存在,创建文件夹成功");
}
else {
    System.out.println("父级路径不存在,创建文件夹失败");
}

2.删除

1.方法名称:delete()

2.使用规范:既可以删除文件,也可以删除文件夹

3.注意:

  • 删除的时候不走回收站,直接删除
  • 不能删除非空文件夹

例:

System.out.println("------delete------");
System.out.println(file.getPath());//
if (file.delete()) {
    System.out.println("删除成功");
}
else
{
    System.out.println("删除失败");
}
System.out.println(file.exists());//false

4.deleteOnExit(): 在虚拟机终止时,请求删除此抽象路径名的文件或者目录,保证文件异常时也可以删除文件(注意:谨慎使用)

3.重命名

方法名称:renameTo(File dest)

注意事项:

  • 方法的调用者,是一个File对象,方法的参数是另外一个File对象
  • 调用者是当前修改之前的路径对象,参数是要修改为的路径对象
  • 如果改了父级路径,就是剪切+重命名,如果不改父级路径就是重命名
System.out.println("------renameTo------");
System.out.println(file1.getPath());//.\基础语法\src\com\textFile\1.txt
File file = new File(".\\基础语法\\src\\com\\textFile\\folder2\\2.txt");
if (file1.renameTo(file)) {
    System.out.println("重命名成功");
    System.out.println(file1.getPath());//.\基础语法\src\com\textFile\1.txt
    System.out.println(file.getPath());//
}else
{
    System.out.println("重命名失败");
}

4.获取

  • getName():获取文件或文件夹名称
  • getPath():返回的是绝对路径,可以是相对路径,但是目录要指定
  • getAbsolutePath():获取绝对路径
  • length():获取文件的大小(字节为单位)
  • getParent():获取文件的父路径
  • lastModified():获取文件最后一次修改的时间

5.判断

  • exists():判断指定的文件或者文件夹是否存在
  • isFile():判断是否是一个文件;如果不存在,则为false
  • isDirectory():判断是否是一个文件夹
  • isHidden():判断指定的文件是否是隐藏文件
  • isAbsolute():判断指定的文件或文件夹是否是在绝对路径下
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值