JAVA study notes—collection of commonly used classes

inner class

Member inner class, static inner class, local inner class, anonymous inner class

Concept: Define a complete class inside a class

Features:

  • After compilation, independent bytecode files can be generated
  • Inner classes can directly access private members of outer classes without breaking encapsulation
  • Provides necessary internal functional components to external classes
//身体
public class Body {
    
    
    private String name;
    //头部
    class Header{
    
    
      	//也会生成class文件 同时生成构造函数
      	//可以直接访问外部类私有成员
        public void showName(){
    
    
            System.out.println(name);
        }
    }
}

member inner class

  • Defined inside a class, a class at the same level as instance variables and instance methods
  • An instance part of an external class. When creating an internal class object, it must rely on the external class object.
  • When there are attributes with the same name in the outer class and the inner class, the inner class attributes will be accessed first.
  • Static members cannot be defined in member inner classes and can contain static constants (final)
//外部类
public class Outer {
    
    
    //实例变量
    private String name = "张三";
    private int age = 20;

    //内部类
    class Inner{
    
    
        private String address = "北京";
        private String phone = "110";
        private String name = "李四";
        //方法
        public void show(){
    
    
            //打印外部类属性 此时有重名属性name
            System.out.println(Outer.this.name); // 张三
            System.out.println(age);
            //打印内部类中的属性
            System.out.println(name); // 李四
            System.out.println(address);
            System.out.println(phone);
        }
    }
}

public class TestOuter {
    
    
    public static void main(String[] args) {
    
    
        // 创建外部类对象
        Outer outer = new Outer();
        // 创建内部类对象
        Outer.Inner inner = outer.new Inner();

        //一步到位
        Outer.Inner inner1 = new Outer().new Inner();
        inner1.show();
    }
}

static inner class

  • Does not rely on external class objects, can be created directly or accessed through class names, and static members can be declared
//外部类
public class Outer {
    
    
    private String name = "张三";
    private int age = 18;

    //静态内部类,和外部类相同
    static class Inner {
    
    
        private String address = "上海";
        private String phone = "110";
        //静态成员
        private static int count = 1000;

        public void show() {
    
    
            //调用外部类属性
            //1.先创建外部类对象
            Outer outer = new Outer();
            //2.调用外部类对象的属性
            System.out.println(outer.name);
            System.out.println(outer.age);
            //调用静态内部类属性
            System.out.println(address);
            System.out.println(phone);
            //调用静态内部类的静态属性
            System.out.println(Inner.count);
        }
    }

//测试类
public class TestOuter {
    
    
    public static void main(String[] args) {
    
    
        //直接创建静态内部类对象
        Outer.Inner inner = new Outer.Inner();
        inner.show();
    }
}

local inner class

  • Defined in an external class method , the scope and created object scope are limited to the current method
  • When a local inner class accesses a local variable in the current method of an outer class, the variable must be modified to final because it cannot guarantee that the life cycle of the variable is the same as itself.
  • Limit the scope of use of a class
//外部类
public class Outer {
    
    
    private String name = "刘德华";
    private int age = 20;

    public void show() {
    
    
        //定义局部变量
        final String address = "深圳";
        //局部内部类 注意:不可以添加任何访问修饰符
        class Inner {
    
    
            //局部内部类的属性
            private String phone = "158";
            private String email = "[email protected]";

            public void show2() {
    
    
                //访问外部类的属性
                System.out.println(Outer.this.name);
                System.out.println(Outer.this.age);
                //访问内部类的属性
                System.out.println(this.phone);
                System.out.println(this.email);
                //访问局部变量,jdk1.7要求,变量必须是常量,jdk1.8 自动添加final
                System.out.println(address);
            }
        }
        //创建局部内部类对象
        Inner inner = new Inner();
        inner.show2();
    }
}
public class TestOuter {
    
    
    public static void main(String[] args) {
    
    
        Outer outer = new Outer();
        outer.show();
    }
}

anonymous inner class

  • Local inner class without class name (all characteristics are the same as local inner class)
  • Must inherit a parent class or implement an interface
  • The syntax of defining a class, implementing a class, and creating an object is merged. Only one object of this class can be created.
  • Advantages: Reduce the amount of code
  • Disadvantages: poor readability
//接口
public interface USB {
    
    
    //服务
    void service();
}
public class Mouse implements USB{
    
    
    @Override
    public void service() {
    
    
        System.out.println("连接电脑成功,鼠标开始工作");
    }
}
public class TestUsb {
    
    
    public static void main(String[] args) {
    
    
        
        //创建一个接口类型的变量
        USB usb = new Mouse();
        usb.service();

        //局部内部类
        class Fan implements USB {
    
    
            @Override
            public void service() {
    
    
                System.out.println("连接电脑成功,风扇开始工作");
            }
        }
        
        //使用局部内部类创建对象
        USB usb = new Fan();
        usb.service();
    }

anonymous inner class

public class TestUsb {
    
    
//使用匿名内部类(相当于创建了一个局部内部类)
        USB usb = new USB() {
    
    
            @Override
            public void service() {
    
    
                System.out.println("连接电脑成功,风扇开始工作");
            }
        };
        usb.service();
}

Object class

  • Super class, base class, the direct or indirect parent class of all classes, located at the top level of the inheritance tree
  • Any class that does not write "extends" to indicate that it inherits a certain class will directly inherit from the Object class by default, otherwise it will be inherited indirectly.
  • The methods defined in the Object class are methods that all objects have
  • The Object type can store any object
    • As a parameter, any object can be accepted
    • As a return value, any object can be returned

getClass method

  • public final Class<?> getClass(){}
  • Returns the actual object type stored in the reference
  • Application: Usually used to determine whether the actual stored object types in two references are consistent.
public class TestStudent {
    
    
    public static void main(String[] args) {
    
    
        Student s1 = new Student("aaa", 20);
        Student s2 = new Student("bbb", 30);
        //判断s1和s2是不是同一个类型
        Class class1 = s1.getClass();
        Class class2 = s2.getClass();
        if (class1 == class2) {
    
    
            System.out.println("s1和s2属于同一个类型");
        } else {
    
    
            System.out.println("s1和s2不属于同一个类型");
        }
    }
}

hashCode method

  • public int hashCode(){}
  • Returns the hash code value of this object
  • The hash value is an int type value calculated using the hash algorithm based on the object's address or string or number.
  • Generally, the same object returns the same hash code
//hashCode方法
Student s3=s1;
System.out.println(s1.hashCode());//356573597
System.out.println(s2.hashCode());//1735600054
System.out.println(s3.hashCode());//356573597

toString method

  • public String toSring(){}
  • Returns the string representation (representation) of this object
  • This method can be overridden according to program requirements, such as: displaying each attribute value of the object
//3. toString方法
System.out.println(s1.toString());//Demo07.Student@1540e19d
System.out.println(s2.toString());//Demo07.Student@677327b6

//原码
public String toString() {
    
    
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

@Override
    public String toString() {
    
    
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
}

equals method

  • public boolean equals(Object obj){}
  • The default implementation is (this == obj), which compares whether the addresses of two objects are the same.
  • Can be overwritten to compare whether the contents of two objects are the same
//4. equals方法 判断两个对象是否相等
System.out.println(s1.equals(s2)); // false
Student s4 = new Student("小明", 17);
Student s5 = new Student("小明", 17);
System.out.println(s4.equals(s5)); // false 堆中地址不同


// 重写 改变其比较内容
/*
步骤  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 Student){
    
    
    // 4.强制类型转换
    Student s = (Student)obj;
    // 5. 比较属性
    if(this.name.equals(s.getName()) && this.age == s.getAge()){
    
    
      return true;
    }
  }
  return false;
}

finalize method

  • When an object is determined to be a garbage object, this method is automatically called by the JVM to mark the garbage object and enter the recycling queue.
  • Garbage object: When there is no valid reference pointing to this object, it is a garbage object.
  • Garbage collection: garbage objects are destroyed by gc and release data storage space
  • Automatic recycling mechanism: The JVM's memory is exhausted and all garbage objects are recycled at once
  • Manual recycling mechanism: Use **System.gc();** to notify the JVM to perform garbage collection
@Override
protected void finalize() throws Throwable{
    
    
  sout(this.name + "对象被回收了");
}
//测试类
public class TestStudent2 {
    
    
    public static void main(String[] args) {
    
    
        Student s1 = new Student("aaa", 29); // 不是垃圾
        Student s2 = new Student("bbb", 29); // 不是垃圾
        Student s3 = new Student("ccc", 29); // 不是垃圾
        Student s4 = new Student("ddd", 29); // 不是垃圾
        Student s5 = new Student("eee", 29); // 不是垃圾
        new Student("bbb", 30); // 是垃圾 会被回收
        //回收垃圾
        System.gc();
        System.out.println("回收垃圾");
        // 打印出 “回收垃圾
        // bbb对象被回收了
    }
}

Packaging

  • Reference data types corresponding to basic data types
  • Object can unify all data, and the default value of the wrapper class is null.
  • Basic types and local variables exist in stack space, and reference types store heap space.
Basic data types type of packaging
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character

Type conversion, boxing, and unboxing

  • 8 wrapper classes provide conversion methods between different types

    • Six common methods provided in the Number parent class

      1. parseXXX( )static method

      2. valueOf( )static method

  • Note: Type compatibility must be ensured, otherwise a NumberFormatException will be thrown

psvm(String[] args){
    
    
  // 装箱, 基本类型 → 引用类型(对象)  栈->堆
  // 基本类型
  int num1 = 18;
  // 使用Integer类创建对象
  Integer integer1 = new Integer(num1);
  Integer integer2 = Integer.valueOf(num1);
  
  // 拆箱, 引用类型 → 基本类型        堆->栈
  Integer integer3 = new Integer(100);
  int num2 = integer3.intValue();
  
  // 上述为jdk1.5之前方法,之后提供了自动装箱拆箱
  int age = 30;
  // 自动装箱
  Integer integer4 = age;
  // 自动拆箱
  int age2 = integer4;
  
  // 基本类型和字符串之间转换
  // 1. 基本类型转成字符串
  int n1 = 100;
  // 1.1 使用+号
  String s1 = n1 + "";
  // 1.2 使用Integer中的toString()方法
  String s2 = Integer.toString(n1);
  String s2 = Integer.toString(n1, x); // x为进制要求
  String s3 = Integer.toBinaryString(n1);//转换成二进制
  
  // 2. 字符串转成基本类型
  String str = "150";
  // 使用Integer.parseXXX();
  int n2 = Integer.parseInt(str);
  
  // boolean 字符串形式转成基本类型,"true" ---> true 非“true ———> false
  String str2 = "true";
  boolean b1 = Boolean.parseBoolean(str2);
}

integer buffer

  • Java pre-creates 256 commonly used certificate packaging type objects
  • In actual applications, reuse created objects
public static void main(String[] args) {
    
    
        //面试题
        Integer integer1 = new Integer(100);
        Integer integer2 = new Integer(100);
        System.out.println(integer1 == integer2);//false

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

        Integer integer5 = 200;// 自动装箱
        Integer integer6 = 200;
        System.out.println(integer5==integer6);//false
        //valueOf 方法
        // 因为缓存区数组 [-128, 127] 在这之内地址一样
        // 不在cache数组区间内 则 new Integer(i);
        /*
        public static Integer valueOf(int i) {
            if (i >= Integer.IntegerCache.low && i <= Integer.IntegerCache.high)
                return Integer.IntegerCache.cache[i + (-Integer.IntegerCache.low)];
            return new Integer(i);
        }
         */
    }

String class

  • Strings are constants and cannot be changed after creation.
  • String literals are stored in a string pool and can be shared
  • String s = "Hello";Generate an object and store it in the string pool
  • String s = new String("Hello");Generate two objects, one for the heap and one for the pool.
public static void main(String[] args) {
    
    
        //产生一个对象,字符串池中存储
        String name = "hello";//"hello" 常量存储在字符串池中
        //不可变性
        name = "zhansgan"; // "张三"赋值给name,给字符串赋值是没有修改数据
        //不是将字符串池中"hello"的值更改,而是重新在字符串池中开辟新的空间
        System.out.println(name);

        String name2 = "zhangsan";//指向原来字符串池中的"zhansgan"
        //字符串字面值存储在字符串池中,可以共享

        //演示字符串的另一种创建方式
        // 产生两个对象,堆、池各一个
        String str1 = new String("java");
        String str2 = new String("java");
        System.out.println(str1==str2);//false
}

Common methods

public class Demo11 {
    
    
    public static void main(String[] args) {
    
    
        // 1. length(); 返回字符串长度
        // 2. charAt(int index); 返回某个位置的字符
        // 3. contains(String str); 判断是否包含某个字符串
        String content = "java是最好的语言";
        System.out.println(content.length());//10
        System.out.println(content.charAt(1));//a
        System.out.println(content.contains("java"));//true

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

        // 7. trim(); //去掉字符串前后空格
        // 8. toUpperCase(); toLowerCase(); 转换大小写
        // 9. endWith(str); startWith(str);  判断是否以str 结尾、开头
        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 "));//true
        System.out.println(ct.startsWith(" hello"));//true

        // 10. replace(char old, char new); 用心的字符或字符串替换旧的字符或字符串
        // 11. split(); 对字符串拆分
        System.out.println(ct.replace("hello", "fuck"));// fuck world
        String say = "java is the best language";
        String[] arr = say.split(" ");// "[ ,]+" 表示空格 逗号切分 +号表示切分可以多个 比如多个空格
        for (String s : arr) {
    
    
            System.out.println(s);
        }
        /* 打印
        java
        is
        the
        best
        language
         */

        // 补充两个equals/compareTo();比较大小
        String s1 = "hello";
        String s2 = "HELLO";
        System.out.println(s1.equals(s2));//false
        System.out.println(s1.equalsIgnoreCase(s2));// 忽略大小写比较true

        // compareTo(); 两字符不同时比较字符字典序的ascii码
        // 字符相同时比较长度 返回差值
        String s3 = "abc";//97
        String s4 = "xyzaa";//120
        System.out.println(s3.compareTo(s4));//-23

        String s5 = "abc";//97
        String s6 = "abcxyz";//120
        System.out.println(s5.compareTo(s6));//-3,比较长度
    }
}

Case presentation

need:

  1. Known String str = “this is a text”;
  2. Get the words in str individually
  3. Replace text in str with practice
  4. Insert an easy before text
  5. Capitalize the first letter of each word
public class Demo12 {
    
    
    public static void main(String[] args) {
    
    
        //1.将str中的单词单独获取
        String str = "this is a text";
        String[] arr = str.split(" ");
        for (String s : arr) {
    
    
            System.out.println(s);
        }
        //2.将str中的text替换成practice
        String str2 = str.replace("text", "practice");
        System.out.println(str2);//this is a practice
        //3.在text前面插入一个easy
        String str3 = str.replace("text", "easy text");
        System.out.println(str3);//this is a easy text
        //4.将每个单词的首字母改为大写
        for (int i = 0; i < arr.length; i++) {
    
    
            char first = arr[i].charAt(0);
            char upperFirst = Character.toUpperCase(first);
            String news = upperFirst + arr[i].substring(1); //substring 截取,开始脚标
            System.out.print(news + " ");//This Is A Text 
        }
    }
}

mutable string

  • StringBuffer: Variable-length string, slow operation, thread-safe
  • StringBuilder: can extend strings, runs fast, and is thread-unsafe
  • Difference from String
    1. More efficient than String
    2. Saves memory than String
public static void main(String[] args) {
    
    
        // StringBuffer 和 StringBuilder 用法一致
        StringBuffer sb = new StringBuffer();
        // 1. append(); 追加
        sb.append("java");
        System.out.println(sb.toString());//java
        // 2. insert(); 添加、插入
        sb.insert(0, "在第一个位置插入");
        System.out.println(sb.toString());//在第一个位置插入java
        // 3.replace(); 替换
        sb.replace(0, 3, "hello"); // 左闭右开
        System.out.println(sb.toString());//hello个位置插入java
        // 4. delete(); 删除
        sb.delete(0, 5); // 左闭右开
        System.out.println(sb.toString());
        // 5. 反转
        sb.reverse();
        System.out.println(sb.toString());
        // 6. 清空
        sb.delete(0, sb.length());
        System.out.println(sb.toString());
}

Time efficiency analysis

//开始时间
long start = System.currentTimeMillis();
String string = "";
for (int i = 0; i < 9999; i++) {
    
    
	string += i+" ";
}
System.out.println(string);
long end = System.currentTimeMillis();
System.out.println("用时:"+(end-start));//用时:514

long start2 = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 9999; i++) {
    
    
	sb.append(i);
}
System.out.println(sb.toString());
long end2 = System.currentTimeMillis();
System.out.println("用时:"+(end2-start2));//用时:2

BigDecimal class

  • Location java.mathin package
  • Function to accurately calculate floating point numbers
  • How to createBigDecimal bd = new BigDecimal("1.0");
public static void main(String[] args) {
    
    
        double d1 = 1.0;
        double d2 = 0.9;
        System.out.println(d1 - d2);//0.09999999999999998
        //面试题
        double result = (1.4 - 0.5) / 0.9;
        System.out.println(result);//0.9999999999999999
        //BigDecimal ,大的浮点数精确计算
        BigDecimal bd1 = new BigDecimal("1.0");//需要用字符串
        BigDecimal bd2 = new BigDecimal("0.9");
        // 减法
        BigDecimal r1 = bd1.subtract(bd2);
        System.out.println(r1);//0.1
        //加法
        BigDecimal r2 = bd1.add(bd2);
        System.out.println(r2);
        //乘法
        BigDecimal r3 = bd1.multiply(bd2);
        System.out.println(r3);
        //除法
        BigDecimal r4 = new BigDecimal("1.4").subtract(new BigDecimal("0.5")).divide(new BigDecimal("0.9"));
        System.out.println(r4);
        //除不尽时 x填保留位数 后面为四舍五入之意
        BigDecimal r5 = new BigDecimal("10").divide(new BigDecimal("3"),2,BigDecimal.ROUND_HALF_EVEN);//3.33
        System.out.println(r5);
}

Data class

  • Date represents a specific instant, accurate to milliseconds. Most of the methods in the Date class have been replaced by methods in the Calendar class
  • Time unit: 1s = 1,000ms = 1,000,000 μs = 1,000,000,000 = ns
public static void main(String[] args) {
    
    
        // 1 创建Date对象
        //今天
        Date date1 = new Date();
        System.out.println(date1.toString());//Fri Jan 06 21:15:33 CST 2023
        System.out.println(date1.toLocaleString());//2023-1-6 21:16:01
        //昨天
        Date date2 = new Date(date1.getTime()-1000*60*60*24);
        System.out.println(date2.toLocaleString());//2023-1-5 21:17:08

        // 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(date2);
        System.out.println(d); // 多的为1 少的为 -1

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

Calendar class

  • Calendar provides methods to get or set various calendar fields
  • The constructor protected Calendar();cannot be created directly because it is protected.
  • Other methods
method name illustrate
static Calendar getInstance() Get calendar using default time zone and region
void set(int year, int month, int date, int hourofday, int minute, int second) Set the year, month, day, hour, minute, and second of the calendar
int get(int field) Returns the value of the given calendar field. Fields such as year, month, day
void setTime(Date date) Sets this calendar time with the given date
Date getTime() Returns a date representing the time of this calendar
void add(int field, int amount) Add or subtract the amount of time to a specified field according to the calendar's rules
long getTimeInMilles() Returns the time value of this calendar in milliseconds
    public static void main(String[] args) {
    
    
        // 1. 创建 Calendar 对象
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar.getTime().toLocaleString());//2023-1-6 21:50:13
        System.out.println(calendar.getTimeInMillis());//1673013029291
        // 2. 获取时间信息
        // 获取年
        int year = calendar.get(Calendar.YEAR);//2023
        // 获取月 从 0 - 11
        int month = calendar.get(Calendar.MONTH);//0
        // 日
        int day = calendar.get(Calendar.DAY_OF_MONTH);//6
        //小时
        int hour = calendar.get(Calendar.HOUR_OF_DAY);//HOUR_OF_DAY 24小时  HOUR 12小时
        //分钟
        int minute = calendar.get(Calendar.MINUTE);
        //秒
        int second = calendar.get(Calendar.SECOND);
        //2023年01月6日 21:55:36
        System.out.println(year + "年" + month + 1 + "月" + day + "日 " + hour + ":" + minute + ":" + second);
        // 3. 修改时间
        Calendar calendar2 = Calendar.getInstance();
        calendar2.set(Calendar.DAY_OF_MONTH, 5);
        System.out.println(calendar2.getTime().toLocaleString());//2023-1-5 21:57:02
        // 4. add修改时间
        calendar2.add(Calendar.HOUR, 1); // x为正就加 负就减
        System.out.println(calendar2.getTime().toLocaleString());//2023-1-5 22:57:40
        // 5. 补充方法
        int max = calendar2.getActualMaximum(Calendar.DAY_OF_MONTH);// 月数最大天数 31
        int min = calendar2.getActualMinimum(Calendar.DAY_OF_MONTH);//1
    }

SimpleDateFormat class

  • SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-dependent manner
  • Format (date → text), parse (text → date)
  • Commonly used time pattern letters
letter date or time Example
y Year 2019
08 mid-year month 08
d Days in the month 10
H Hour of day (0-23) 22
m minute 16
s Second 59
S millisecond 356
public static void main(String[] args) {
    
    
        // 1. 创建对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd");
        // 2. 创建Date
        Date date = new Date();
        // 格式化date(日期→字符串)
        String str = sdf.format(date);
        System.out.println(str);//2023年01月06日 22:07:41
        // 解析(字符串→时间)
        Date date2 = null;
        try {
    
    
            date2 = sdf.parse("2001年2月24日 10:24:55");
        } catch (ParseException e) {
    
    
            e.printStackTrace();
        }
        System.out.println(date2);//Sat Feb 24 10:24:55 CST 2001
    }

System class

  • Mainly used to obtain system attribute data and other operations, the construction method is private
method name illustrate
static void arraycopy(…) copy array
static long currentTimeMillis(); Get the current system time and return the millisecond value
static void gc(); It is recommended that the jvm quickly starts the garbage collection period to collect garbage.
static void exit(int status); Exit jvm. If the parameter is 0, it means exiting jvm normally. If it is not 0, it means exiting abnormally.
    public static void main(String[] args) {
    
    
        //1. arraycopy 数组的复制
        //src-原数组 srcPos-从哪个位置开始复制0 dest-目标数组 destPos-目标数组的位置 length-复制的长度
        int[] arr = {
    
    20, 18, 15, 8, 35, 26, 45, 90};
        int[] dest = new int[8];
        //System.arraycopy(src, srcPos, dest, destPos, length);
        System.arraycopy(arr, 0, dest, 0, arr.length - 1);
        for (int i : dest) {
    
    
            System.out.print(i + " ");
        }
        //20 18 15 8 35 26 45 0
        // Arrays.copyOf(original, newLength)
        System.out.println(System.currentTimeMillis());//1673014964891

        //2. currentTimeMillis()
        long start = System.currentTimeMillis();
        for (int i = 0; i < 999999; i++) {
    
    
            for (int j = 0; j < 999999; j++) {
    
    
                int result = i+j;
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("用时:"+(end-start));//用时:10

        //3. gc() 垃圾回收期器回收垃圾
        System.gc();

        //4. exit() 退出jvm 如果参数是0表示正常退出jvm 非0表示异常退出
        System.exit(0);
        System.out.println("---程序结束---");
    }

Guess you like

Origin blog.csdn.net/weixin_42823298/article/details/128585987
Recommended