Summary of JAVA notes (5000 words) Common methods of String class and StringBuffer, System and other classes

Summary of JAVA Notes (5000 words) contains explanations of commonly used APIs (String, Runtime, Object, etc.) [It is recommended to collect and read slowly!!!]

Newcomer creation, I hope everyone can point me to the shortcomings~~
If there is any infringement in this article, the author of the exercise will delete it immediately!

Common tools

Object class

Source: java.lang.Object

The Object class is the parent class of all classes , similar to "the first of all things", including classes written by ourselves, whose parent class is the Object class. If a class does not specify a parent class, it inherits from the Object class by default.


common method
  1. protected Object clone()

    • Create and return a copy (clone) of this object
  2. public boolean equals(Object obj)

    • Compare whether the address values ​​of the two objects are consistent, return true if consistent, otherwise return false
    • It can be understood as *"you == me"*, that is, whether it is the same person (object)
  3. protected void finalize()

    • This method will be called when the GC mechanism is ready to reclaim the object memory space
    • Generally used to release non-java resources (such as open file resources, database connections, etc...)
  4. public int hashCode()

    • Returns the hash value of this object. By default, this method will calculate the hash value based on the address of the object
    • Different objects have different hash values, similar to everyone's ID card
  5. public final class getClass()

    • Returns the class of the current object runtime
    • This class also has a method public String getName(), which can get the full name of the real class of the object through the getName() method of the getClass() class
  6. public String toString()

    • Returns a string representation of the current object
    • The underlying code is as follows:

insert image description here

What is returned is the full path name of the class + hash value; but in actual development, we generally rewrite the toString() method, and will not use Object's toString(), because it has no meaning...

The method toString() is rewritten as follows:

public class Person{
    
    
    //Person类默认继承(extends)Object类
    //成员变量:定义在类中且方法外的变量
    private String name;
    private int age;
    
    @Override
    public String toString() {
    
    
        //重写的toString()方法
        return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
    }
}
  1. public boolean equals(Object obj)
  • To compare whether two objects are equal, the default is the comparison between the address and the address; if the equals method is not overridden, then as long as the Object class is not the same object, the comparison result must be false.

  • If you want to perform a comparison between object contents, you must rewrite this method to achieve content comparison between objects

  • Note: If the object is null, a NullPointException will be thrown when its equals() method is called. The equals method in Objects below solves this problem.

  • The method override code is as follows:

import java.util.Objects;
public class Person {
    
    	
	private String name;
	private int age;
    //有参构造函数
	public Person(String name,int age){
    
    
        this.name = name;
        this.age = age;
    }
    @Override // Person类重写了Object类中的equals()方法
    public boolean equals(Object obj) {
    
    
        // 如果对象地址一样,则认为相同
        if (this == obj)
            return true;
        // 如果参数obj为空,或者类型(类)信息不一样,则认为不同对象,直接返回false
        if (obj == null || getClass() != obj.getClass())
            return false;
        Person person = (Person) obj; // 转换为当前类型
        // 要求基本类型相等,并且将引用类型交给java.util.Objects类的equals静态方法判断结果
        return age == person.age && Objects.equals(name, person.name);
    }
}

Object class

When rewriting the equals() method above, I believe you have seen a reference to the Objects class, so what is this class?

Source: java.util.Objects

After JDK7 , an Objects tool class was added, which provides some methods to manipulate objects. It consists of some static utility methods. These methods are null-save (null pointer safe) or null-tolerant (null pointer tolerance) , used to calculate the hashcode of an object, return a string representation of an object (toString), compare two objects (equals), etc.

As mentioned above, when comparing two objects, the equals method of Object is easy to throw a null pointer exception (when the object is null), and the equals method in the Objects class optimizes this problem. Methods as below:

public static boolean equals(Object obj,Object obj)Determine if two objects are equal (compare content, not address)

The source code is as follows:

insert image description here

It can be seen that its underlying source code also calls Object.equals()the method, and a judgment is made on whether a is null. If it is null, the latter a.equals(b)will not be called, so the NullPointException is cleverly avoided.

common method

In addition to the equals() method that is most used in daily development listed above, there are some other methods

  1. public static int hash(Object values)
    • Generate a hash value for the input value and return
  2. public static boolean isNull(Object obj)
    • Determine whether the input obj is null, return true if it is null, otherwise return false
  3. public static boolean nonNull(Object obj)
    • Determine whether the input obj is not null, return true if it is not null, and return false if it is empty

String class

Source: java.lang.String

All the characters in the double quotes (" ") in the Java program belong to the string (String). After the string is created, its value exists in the memory of the JVM's method area , and its defined value cannot be changed after it is created.

String s1 = "abc";
	   s1 += "d";
System.out.println(s1); // "abcd"
// 方法区内存中有"abc","abcd"两个字符串对象,s1从指向"abc",改变指向,指向了"abcd"

Just because the data of the String type cannot be modified once it is defined, if you create a string that has been created before, the string created later will first look for the character in the string constant pool (instance pool) in the method area memory String, if it does not exist, create one yourself, if it exists, it points to the existing value, so their values ​​can be shared.

String s1 = "abc"; //"abc"在方法区内存的常量池中被定义, s1指向该字符串"abc"
String s2 = "abc"; //s2先在常量池中寻找字符"abc",存在则直接指向它,不存在则自己定义一个,并且指向它
// 总结:内存中只有一个"abc"对象被创建,同时被s1和s2共享。

The string "abc" is equivalent to char[] strs = { 'a' , 'b' , 'c' } ;

String str = "" is equivalent to String str = new String( );

//例如:
String str = "abc";
//相当于:
char data[] = {
    
    'a', 'b', 'c'};    
String str = new String(data); // String底层是靠字符数组实现的
Commonly used construction methods
method name illustrate
new String( ) Creates an empty string object with no content
new String(char[] chs) Create a string object from the contents of a character array
new String(byte[] bys) Create a string object based on the contents of the byte array
String s = “abc” Create a string object by direct assignment, the content is abc
common method
  1. public int length ()
    • Returns the length of this string.
  2. public String concat (String str)
    • Concatenates the specified string to the end of this string.
  3. public char charAt (int index)
    • Returns the char value at the specified index.
  4. public int indexOf (String str) :
    • Returns the index of the first occurrence of the specified substring within this string, or -1 if there is no such occurrence.
  5. public String substring (int beginIndex)
    • Returns a substring, intercepting the string from beginIndex to the end of the string.
  6. public String substring (int beginIndex, int endIndex)
    • Returns a substring, intercepting the string from beginIndex to endIndex, including beginIndex and excluding endIndex.

StringBuffer class

Source: java.lang.Object

​ StringBuilder is a mutable string class. We can regard it as a container. The mutable here means that the content in the StringBuilder object is mutable, because the underlying array is not decorated with keywords, so finalthe The array is mutable, while the underlying array of the String class is finalmodified, so once created, it cannot be changed. This is the biggest difference between the two~

Construction method introduction
constructor name illustrate
new StringBuffer() Constructs a character string buffer with an initial capacity of 16 characters.
new StringBuffer(CharSequence seq) Construct a string buffer containing the specified seq content, the initial capacity is 16+seq length
new StringBuffer(int capacity) constructs a buffer of strings with no characters and specifies its initial capacity
new StringBuffer(String str) Constructs a string buffer initialized to the specified string content str
common method

Note: For all methods involving subscripts in the following StringBuffer class, the subscripts start from 0, and the interval range is half-closed and half-open [begin, end )

  1. append()

    • You can add an arbitrary basic data type or char[] array, and you can specify to intercept the specified part of the char[] array
  2. insert()

    • Data can be inserted at a specified location (data: basic data/array)
  3. charAt(int index)

    • Returns the character at the specified index without changing the original array
  4. codePointAt(int index)

    • Returns the Unicode code corresponding to the character at the specified subscript
  5. delete(int begin, int end)

    • Delete the character at the specified [begin, end) in the string, which will change the original string buffer
  6. deleteCharAt(int index)

    • Delete the character at the index index and change the original string buffer
  7. indexOf(String str)

    • Returns the index of the first occurrence of the specified substring str in the parent string, or returns -1 if it does not appear
  8. indexOf(String str, int index)

    • Returns the index of the first occurrence of the specified substring str in the parent string, and the start search is determined by the index subscript
  9. replace( int begin, int end, String str)

    • Replace the string between [begin, end) with the specified str, which will change the original string buffer, and the replacement character does not include the element at end
  10. reverse()

    • Reversing the contents of the string buffer will change the original string
  11. setCharAt(int index, char ch)

    • Replace the character at the specified index with ch. If the index subscript exceeds the total length of the string buffer, a string index out-of-bounds exception "StringIndexOutOfBoundsException" will be thrown

      code show as below:

      package com.obtk.day18;
      public class Demo01 {
              
              
          public static void main(String[] args) {
              
              
              StringBuffer sb = new StringBuffer("abced");
              //当前总长度为5,不存在下标为7的元素
              sb.setCharAt(7,'p');
              System.out.println(sb);
          }
      }
      

      The execution results are as follows:

    insert image description here

    Note: the total length is 5, and the subscript index is 7, so an exception error will be thrown!!

    How to convert StringBuffer and String to each other?

    You can use the toString() method of the StringBuffer class to convert the StringBuffer to the String type

    The String type can be converted to the StringBuffer type through the constructor of StringBuffer

    For example: new StringBuffer(String str);

    The specific implementation code is as follows:

    public class StringBufferDemo02 {
          
          
        public static void main(String[] args) {
          
          
            //StringBuffer 转换为 String
            StringBuffer sb = new StringBuffer();
            sb.append("hello"); //添加"hello"到字符串缓冲区
            String s = sb; //这个是错误的做法
    		//public String toString()
    		//通过 toString()就可以实现把 StringBuffer转换为String
            String s = sb.toString();
            System.out.println(s);
            // String 转换为 StringBuffer
            String s = "hello";
            
            //StringBuilder sb = s; //这个是错误的做法
            //通过构造方法就可以实现把 String 转换为 StringBuffer
            StringBuffer sb = new StringBuffer(s);
            System.out.println(sb); // 输出hello
        }
    }
    
    String and StringBuffer comparison (difference)
    1. String represents a string constant, once created, the content and length cannot be changed. StringBuffer represents a character container, and its content and length can be modified at any time
    2. It just represents the character type, use the String class, if you want to add or delete operations or change the required string a lot, it is recommended to use StringBuffer
    3. The String class overrides the equals method of the Object class, while the StringBuffer class does not override the equals method of the Object class
    4. String objects can be connected with the operator "+", but StringBuffer objects cannot be connected with "+".

Date time (Date) class

Source: java.util.Date

In daily life, there is one thing that is always with us, that is time. As a popular high-level language, java naturally provides us with some classes that operate on time, such as Date, DateFormat, and SimpleDateFormat. Now, we will start with the above three classes and give some simple introductions to date and time classes.

By consulting the API documentation, we found that Date has multiple constructors, but some of them are outdated, but there are non-outdated constructors that can convert the millisecond value into a date object. The two commonly used construction methods are as follows:

  • new Date(): Allocates a Date object and initializes this object so that it represents the allocated time (to the nearest millisecond)

  • new Date(long date): Allocates a Date object and initializes this object to represent the specified number of milliseconds since a standard base time (called an "epoch" (January 1, 1970 00:00:00 GMT).

public class Demo03 {
    
    
    public static void main(String[] args) {
    
    
        //获取1970-1-1 0:0:0 到其1000毫秒之后的时间
        Date date = new Date(1000);
        //(注:由于我们处于东八区,所以我们的基准时间为1970年1月1日8时0分0秒。)
        //输出1970-1-1 8:0:01 
        System.out.println(date);
    }
}

Most of the methods in the Date class are outdated, and the following are commonly used ones:

  1. public boolean after(Date when)
    • Tests whether this date is after the specified date, returns true if it is, false otherwise
  2. public boolean before(Date when)
    • Tests whether this date is before the specified date, returns true if it is, false otherwise
  3. public long getTime()
    • Returns the total number of milliseconds since January 1, 1970 (Note: 1 second = 1000 milliseconds)

java.text.DateFormat is an abstract class of the date/time formatting subclass. We can use this class to help us complete the conversion between date and text, that is, we can convert back and forth between Date objects and String objects, and convert them into the form we understand.

Construction method

Since DateFormat is an abstract class and cannot be used directly, it needs a common subclass public SimpleDateFormat(String pattern)for instantiation.

Note: The parameter pattern is a string representing the custom format of the date and time

The general format is as follows:

//实例化日期/时间格式化对象SimpleDateFormat,并自定义其转换格式
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

Common format rules are as follows

Identification letter (case sensitive) meaning
y Year
M moon
d Day
H Hour
m minute
s Second

Note: For more detailed format rules, please refer to the API documentation of the SimpleDateFormat class


Common methods of the DateFormat class are

  1. public String format(Date date): convert the Date object into a string according to a certain format
  2. public Date parse(String source): parse the string into a Date object

The code using the format method is as follows:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/*把Date对象转换成String*/
public class Demo04DateFormatMethod {
    
    
    public static void main(String[] args) {
    
    
        Date date = new Date(); //获取日期
        // 创建日期格式化对象,在获取格式化对象时可以指定风格
        DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        //将date对象按照"yyyy年MM月dd日"的格式转换为字符串
        String str = df.format(date);
        System.out.println(str); // 2008年1月23日
    }
}

The code using the parse method is as follows:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/* 把String转换成Date对象*/
public class Demo05DateFormatMethod {
    
    
    public static void main(String[] args) throws ParseException {
    
    
        /*注意:字符串年月日的格式必须和df后面指定的格式一致,否则无法正确转换*/
        //设定df时间对象的日期格式
        DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        String str = "2018年12月11日";
        //将字符串str转换为Date类型的日期格式
        Date date = df.parse(str);
        System.out.println(date); // Tue Dec 11 00:00:00 CST 2018
    }
}

Calendar class

Source: java.util.Calendar

java.util.Calendar is a calendar class that appears after the Date class and replaces many Date methods. This class encapsulates all possible time information as static member variables for easy access. The calendar class is a tool class that facilitates obtaining various time attributes.

Because Calendar is an abstract class, due to language sensitivity, the Calendar class is not created directly when creating an object, but is public static Calendar getInstance()created through a static method and returns a subclass object, as follows

import java.util.Calendar;
public class Demo06CalendarInit {
    
    
    public static void main(String[] args) {
    
    
        //调用Calendar的静态方法创建对象,使用默认时区和语言获得一个日历
        Calendar cal = Calendar.getInstance();
    }    
}
common method
  1. public int get(int field)
    • Returns the value of the given calendar field
  2. public void set(int field, int value)
    • Sets the given calendar field to the given value
  3. public abstract void add(int field, int amount)
    • Adds or subtracts the specified amount of time for the given calendar field
  4. public Date getTime()
    • Returns the current time of a Date type, similar to the current time object created by using Date object new

Calendar provides many member variables that represent a given calendar field

field value meaning
YEAR Year
MONTH month (starts from 0)
DAY_OF_MONTH day of the month
HOUR Hour (12-hour format)
HOUR_OF_DAY Hour (24-hour format)
MINUTE point
SECOND Second
DAY_OF_WEEK day of the week

Note: The week starts on Sunday in Western countries and Monday in China. In the Calendar class, the month is represented by 0-11 representing January-December. The date has a size relationship, the later the time, the greater the time.

package com.obtk.day20;
//导入外部工具包
import java.time.Year;
import java.util.Calendar;

public class Demo02 {
    
    
    public static void main(String[] args) {
    
    
        //实例化日历对象
        Calendar c1 = Calendar.getInstance();
        System.out.println(c1.getTime());
        System.out.println(c1.get(Calendar.DAY_OF_MONTH)); //获取当月天数
        System.out.println(c1.get(Calendar.YEAR));//获取年份
        c1.set(Calendar.YEAR,1995); //设置年份为1995
        System.out.println(c1.get(Calendar.YEAR));
        c1.add(Calendar.YEAR,-3); //当前年份减去3,得到新年份1992
        System.out.println(c1.get(Calendar.YEAR));
        System.out.println(c1.get(Calendar.DAY_OF_WEEK)); // 返回 周几
    }
}   

The output of the above code is as follows:
insert image description here


System class

The java.lang.System class provides a large number of static methods, which can obtain system-related information or system-level operations. In the API documentation of the System class, the commonly used methods are:

  1. public static long currentTimeMillis()

    • Get the millisecond difference between the current system time and 00:00 on January 1, 1970, which is generally used to test the efficiency of the program
  2. public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

    • Intercept elements between specified positions in an array to specified positions in another array
    • Pass in 5 parameters:
      src: indicates the source array
      dest: the target array
      srcPos: the starting position of the copied element in the source array
      descPos: the starting position copied to the target array
      length: the number of copied elements
    • Note: When copying an array, there must be enough space to store the copied elements, otherwise an out-of-bounds exception will occur
  3. static Properties getProperties()

    • Get all the properties of the current system
  4. static String getProperties()

    • Get the current system properties
  5. static long gc()

    • Run the garbage collector and recycle garbage
  6. static void exit(int status)

    • This method is used to terminate the currently running java virtual machine, where the parameter status indicates the status code, if the status code is not 0, it means abnormal termination

    The code demonstration is as follows:

    package com.obtk.day20;
    
    import java.util.Arrays;
    //数组拷贝System.arraycopy()方法演示
    public class Demo03 {
          
          
        public static void main(String[] args) {
          
          
            int[] arr1 = new int[]{
          
          1,2,3,4,5};
            int[] arr2 = new int[]{
          
          6,7,8,9,10};
            //代表从arr1的索引0处复制元素到arr2中索引为2处,并且复制三个元素
            System.arraycopy(arr1,0,arr2,2,3);
            System.out.println(Arrays.toString(arr2));//运行结果: [6,7,1,2,3]
        }
    }
    

    Runtime class

    It is used to represent the running state of the virtual machine, which encapsulates the running of the JVM virtual machine. Every time a virtual machine is started using the java command, it corresponds to a Runtime instance. And there is only one instance; the class is designed using the singleton pattern.

    Singleton mode: To ensure that there is only one instance of an object in a class in the entire system, the way to achieve this function is called singleton mode

    Understand: the benefits of singleton mode:

     1. 节省公共资源
     2. 方便控制
    

Code to test how many cores your computer has:

public class Demo03Runtime {
    
    
    public static void main(String[] args) {
    
    
        //获得一个Runtime的实例
        Runtime rt = Runtime.getRuntime();
        System.out.println("处理器的个数:"+rt.availableProcessors()+"个");
        //默认单位字节
        System.out.println("空闲内存数"+rt.freeMemory()/1024/1024+"M");
        System.out.println("最大可用内存数"+rt.maxMemory()/1024/1024+"M");
    }
}

Open the application program in the system through the code: adopt the exec ( ) method of the Runtime class; The code is as follows:

public class Demo04Runtime2 {
    
    
    public static void main(String[] args) throws IOException, InterruptedException {
    
    
        //创建Runtime实例对象
        Runtime runtime = Runtime.getRuntime();
        //打开记事本 等于产生一个新的进程
        Process process = runtime.exec("notepad.exe");
        //程序休眠3秒  3秒后继续执行下面的程序
        Thread.sleep(3000);
        //杀掉(关闭)进程
        process.destroy();
    }
}

Common search algorithms:

  1. BinarySearch(): binary search method

The code demonstration is as follows:

package com.obtk.day20;

import java.util.Arrays;
/*1.二分查找法*/
public class Demo04 {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = new int[]{
    
    98,78,45,12,45,11,55};
        //二分查找法的前提条件就是元素处于升序状态
        Arrays.sort(arr);
        System.out.println(myBinarySearch(arr,11));
    }
    public static int myBinarySearch(int[] arr,int num){
    
    
        int left = 0; //获取起始下标
        int right = arr.length-1; //获取最后一个元素下标
        while(left <= right){
    
     //left小于right,代表所有区间始终大于等于1
            int mid = (left+right)/2; //获取区间中间值
            //判断中间值是否是我们要找的nunm
            if (arr[mid] == num){
    
    
                return mid; //若是则直接返回其下标
            }else if(arr[mid] > num){
    
    
                //num元素小于中间值,表示mid右边所有值都比num大,所以右边的值都不需要比较,缩短右边区间到mid-1处
                right = mid-1;
            }else if(arr[mid] < num){
    
    
                //num大于中间值,即大于所有中间值mid左边的值,那么左边的值也无需比较,直接缩短左边区间到mid+1处
                left = mid + 1;
            }
        }
        return -1;
    }
}

  1. brute force search

The code demonstration is as follows:

package com.obtk.day20;

import java.util.Arrays;
/*2.暴力搜索法:找出有序数列中指定元素的索引*/
public class Demo05 {
    
    
    public static void main(String[] args) {
    
    
        int[] arr = new int[]{
    
    98,78,45,12,45,11,55};
        Arrays.sort(arr); //搜索前对元素进行排序
        System.out.println(Search(arr,11));
    }
    public static int Search(int arr[],int num){
    
    
        for (int i = 0; i < arr.length; i++) {
    
    
            if (arr[i] == num){
    
     //通过循环一个一个比较
                return i;
            }
        }
        //找不到元素就返回-1
        return -1;
    }
}

Author: Hu Yi
Time: November 29, 2021 22:06:43 It
is not easy to create, I hope you will like and support the following~~

Guess you like

Origin blog.csdn.net/qq_56880706/article/details/121620837