Summary of common Java classes

Posted by millsy007 on Sun, 16 Jan 2022 14:23:22 +0100

Object

Object class is the parent class of all classes, that is, all classes in Java inherit object by default, and subclasses can use all methods of object.

public class Test {
    
}

amount to

public class Test extends Object {

}

The Object class is the root of the class hierarchy. The Object class is the only class in Java that does not have a parent class.

clone()

The clone() method is used to create and return a copy of an object.

The clone() method is a shallow copy. The object referenced by the attribute in the object will only copy the reference address without reallocating the memory of the referenced object. The corresponding deep copy will recreate even the referenced object.

public class Test implements Cloneable {

    String name;
    int age;

    public static void main(String[] args) throws CloneNotSupportedException {

        Test obj1 = new Test();
        obj1.name = "jason";
        obj1.age = 18;

        System.out.println(obj1.name);  // jason
        System.out.println(obj1.age);   // 18

        // Create a copy of obj1
        Test obj2 = (Test) obj1.clone();

        System.out.println(obj2.name);  // jason
        System.out.println(obj2.age);   // 18

    }
}

toString()

The toString() method returns a string representation of the object.

Default return format: hexadecimal string of object class name + @ + hashCode.

public class Test {

    public static void main(String[] args) {

        Object obj1 = new Object();
        System.out.println(obj1.toString()); // java.lang.Object@1b6d3586

        Object obj2 = new Object();
        System.out.println(obj2.toString()); // java.lang.Object@4554617c

        // The array element value returns a string expression
        String[] arr = {"a", "b", "c"};
        System.out.println(arr[0].toString()); // a
        System.out.println(arr[1].toString()); // b
    }
}

You can also override the toString() method

public class Test {

    public static void main(String[] args) {

        Test test = new Test();
        System.out.println(test.toString()); // Test
    }

    public String toString() {
        return "Test";
    }
}

getClass()

The getClass() method is used to get the class of the runtime object of the object.

public class Test {

    public static void main(String[] args) {

        Object obj = new Object();
        System.out.println(obj.getClass()); // class java.lang.Object

        String str = new String();
        System.out.println(str.getClass()); // class java.lang.String

        Test test = new Test();
        System.out.println(test.getClass()); // class Test
    }
}

equals()

The equals() method is used to compare whether two objects are equal.

The equals() method directly judges whether the values of this and obj are equal, that is, it is used to judge whether the object calling equals and the object referenced by the formal parameter obj are the same object. The so-called same object refers to the same block of storage unit in memory. If this and obj point to the hi same block of memory object, it returns true. If this and obj do not point to the same block of memory, Returns false.

Note: even two different memory objects with identical contents return false.

public class Test {

    public static void main(String[] args) {

        // Compare two objects

        Object obj1 = new Object();
        Object obj2 = new Object();

        // Different objects have different memory addresses and are not equal. false is returned
        System.out.println(obj1.equals(obj2)); // false

        // Object reference. The memory addresses are the same and equal. true is returned
        Object obj3 = obj1;
        System.out.println(obj1.equals(obj3)); // true

        // The String class overrides the equals() method to compare whether two strings are equal

        String str1 = new String();
        String str2 = new String();

        System.out.println(str1.equals(str2)); // true
        System.out.println(str1 == str2); // false

        str1 = "a";
        str2 = "a";

        System.out.println(str1.equals(str2)); // true
        System.out.println(str1 == str2); // true
    }
}

==And the equals() method

  • ==You can compare whether the values of the variables of two basic data classes are equal, or whether the first address of the object is the same.
  • The equals() method can only compare whether the first address of an object is the same.

hashCode()

The hashCode() method is used to get the hash value of the object.

The hashCode() method is used for hash lookup, which can reduce the number of times of using equals() in the lookup. If you override the equals method, you generally have to override the hashCode() method. This method is used in some collections with hash function.

import java.util.ArrayList;

public class Test {

    public static void main(String[] args) {

        Object obj1 = new Object();
        Object obj2 = new Object();

        System.out.println(obj1.hashCode()); // 460141958
        System.out.println(obj2.hashCode()); // 1163157884

        String str = new String();
        System.out.println(str.hashCode()); // 0

        ArrayList<Integer> arr = new ArrayList<>();
        System.out.println(arr.hashCode()); // 1
    }
}

Generally, obj 1 must be met equals(obj2) == true. Can launch obj 1 hash Code() == obj2. hashCode(), but equal hashcodes do not necessarily satisfy equals. However, in order to improve efficiency, we should try to make the above two conditions close to equivalence.

wait()

The wait() method puts the current thread into a wait state. Until another thread calls the notify() method or notifyAll() method of this object.

notify() wakes up a thread waiting on the object.

notifyAll() wakes up all threads waiting on the object.

import java.util.Date;

class WaitTest {
    public static void main(String[] args) {
        ThreadA threadA = new ThreadA("threadA");
        synchronized (threadA) {
            try {
                // Start thread
                threadA.start();
                System.out.println(Thread.currentThread().getName() + " wait() " + new Date());
                // The main thread waits for ta to wake up via notify.
                threadA.wait();// Instead of making the ta thread wait, the thread currently executing the wait waits
                System.out.println(Thread.currentThread().getName() + " continue " + new Date());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

class ThreadA extends Thread {
    public ThreadA(String name) {
        super(name);
    }

    @Override
    public void run() {
        synchronized (this) {
            try {
                Thread.sleep(1000); // Block the current thread for 1 second
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " call notify()");
            this.notify();
        }
    }
}

Output results:

main wait() Sat Jul 24 13:03:57 CST 2021
threadA call notify()
main continue Sat Jul 24 13:03:58 CST 2021

finalize()

The finalize() method is used for the operation triggered when the instance is collected by the garbage collector.

class Test {
    public static void main(String[] args) {
        User u1 = new User(1);
        User u2 = new User(2);
        User u3 = new User(3);

        u2 = u3 = null;
        System.gc();
    }
}

class User {
    private int id;

    public User(int id) {
        this.id = id;
        System.out.println("User Object " + id + " is created");
    }

    protected void finalize() throws java.lang.Throwable {
        super.finalize();
        System.out.println("User Object " + id + " is disposed");
    }
}

About garbage collection:

  1. Objects may not be garbage collected. As long as the program is not on the verge of running out of storage space, the space occupied by objects will not be used up

To release.

  1. Garbage collection is not equal to "Deconstruction".

  2. Garbage collection is only memory related. The only reason to use garbage collection is to recycle memory that is no longer used by the program.

Purpose of finalize():

No matter how the object is created, the garbage collector is responsible for freeing all the memory occupied by the object.

This limits the need for finalize() to a special case where storage space is allocated to objects in a way other than the way they are created. However, this situation usually occurs when the local method is used, and the local method is a way to call non Java code in Java.

String

In Java, strings belong to objects. Java provides String classes to create and manipulate strings.

Creation method

class Test {
    public static void main(String[] args) {

        // The object created by direct assignment is the constant pool in the method area
        String str1 = "hello";

        // The string object created by the construction method is in heap memory
        String str2 = new String("hello");

        // Reference passing, str3 directly points to the heap memory address of st2
        String str3 = str2;

        String str4 = "hello";

        System.out.println(str1 == str2); // false
        System.out.println(str1 == str3); // false
        System.out.println(str3 == str2); // true
        System.out.println(str1 == str4); // true
    }
}

common method

String judgment

methoddescribe
boolean equals(Object obj)Compare whether the contents of the string are the same
boolean equalsIgnoreCase(String str)Compare whether the contents of the string are the same, ignoring case
boolean startsWith(String str)Determines whether the string object starts with the specified str
boolean endsWith(String str)Determines whether the string object ends with the specified str

String interception

methoddescribe
int length()Gets the length of the string, which is actually the number of characters
char charAt(int index)Gets the character at the specified index
int indexOf(String str)Gets the index of the first occurrence of str in a string object
String substring(int start)Intercept string from start
String substring(int start,int end)Intercept the string from start to end. Including start, excluding end

String conversion

methoddescribe
char[] toCharArray()Convert string to character array
String toLowerCase()Convert string to lowercase string
String toUpperCase()Convert string to uppercase string

Other methods

methoddescribe
String trim()Remove spaces at both ends of string
String[] split(String str)Splits the string according to the specified symbol

StringBuilder and StringBuffer

StringBuilder is a variable character sequence. It inherits from AbstractStringBuilder and implements the CharSequence interface.

StringBuffer is also a subclass inherited from AbstractStringBuilder;

However, StringBuilder is different from StringBuffer. The former is non thread safe and the latter is thread safe.

common method

methoddescribe
public StringBuffer append(String s)Appends the specified string to this character sequence.
public StringBuffer reverse()Replace this character sequence with its inverted form.
public delete(int start, int end)Remove characters from substrings of this sequence.
public insert(int offset, int i)Inserts the string representation of the int parameter into this sequence.
insert(int offset, String str)Insert the string of str parameter into this sequence.
replace(int start, int end, String str)Replaces the characters in the substring of this sequence with the characters in the given String.
class Test {
    public static void main(String[] args) {

        StringBuilder sb = new StringBuilder(10);
        // StringBuffer sb = new StringBuffer(10);

        sb.append("Test..");
        System.out.println(sb); // Test..

        sb.append("!");
        System.out.println(sb); // Test..!

        sb.insert(6, "Java");
        System.out.println(sb); // Test..Java!

        sb.delete(4, 6);
        System.out.println(sb); // TestJava!
    }
}

The usage of StringBuilder is similar to that of StringBuffer.

Differences among String, StringBuilder and StringBuffer:

The first thing to note is:

  • String constant

  • StringBuilder string variable (non thread safe)

  • StringBuffer string variable (thread safe)

In most cases, the three are compared in terms of execution speed: StringBuilder > StringBuffer > string

Summary of the use of the three:

  • If you want to manipulate a small amount of data, use = String

  • Single thread operation large amount of data in string buffer = StringBuilder

  • Multithreaded operation: operate a large amount of data in the string buffer = StringBuffer

Number

All wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.

Packaging

PackagingBasic data type
Booleanboolean
Byteshort
Shortshort
Integerint
Longlong
Characterchar
Floatfloat
Doubledouble

usage method

Realize the conversion between int and Integer

class Test {
    public static void main(String[] args) {

        int m = 500;
        Integer obj = new Integer(m);
        int n = obj.intValue();

        System.out.println(n); // 500

        Integer obj1 = new Integer(500);
        System.out.println(obj.equals(obj1)); // true
    }
}

Converts a string to an integer

class Test {
    public static void main(String[] args) {

        String[] str = {"123", "123abc", "abc123", "abcxyz"};
        for (String str1 : str) {
            try {
                int m = Integer.parseInt(str1, 10);
                System.out.println(str1 + " Can be converted to an integer " + m);
            } catch (Exception e) {
                System.out.println(str1 + " Cannot convert to integer");
            }
        }
    }
}

Output results:

123 Can be converted to integer 123
123abc Cannot convert to integer
abc123 Cannot convert to integer
abcxyz Cannot convert to integer

Converts an integer to a string

class Test {
    public static void main(String[] args) {

        int m = 500;
        String s = Integer.toString(m);
        System.out.println(s); // 500

        String s2 = m + "a";
        System.out.println(s2); // 500a
    }
}

Math

Java's Math contains properties and methods for performing basic mathematical operations, such as elementary exponents, logarithms, square roots, and trigonometric functions.

constant value

constantdescribe
Math.PIRecorded pi
Math.EConstant of record e

common method

methoddescribe
Math.absReturns the absolute value of the parameter.
Math.sinEvaluates the sine of the specified double type parameter.
Math.cosEvaluates the cosine of the specified double type parameter.
Math.tanEvaluates the tangent value of the specified double type parameter.
Math.toDegreesConverts an angle to radians.
Math.ceilGet the largest integer not less than a certain number.
Math.floorGet the largest integer not greater than a certain number.
Math.IEEEremainderSeeking remainder
Math.maxReturns the maximum of the two parameters.
Math.minReturns the smallest of the two parameters.
Math.sqrtFind the arithmetic square root of the parameter.
Math.powFind any power of a number and throw arithmetexception to handle overflow exception
Math.expReturns the parameter power of the base e of a natural number.
Math.log10Base 10 logarithm
Math.logReturns the logarithm of the natural base of a parameter.
Math.rintFind the integer nearest to a number (which may be larger or smaller than a number).
Math.roundAs above, it returns int type or long type (the previous function returns double type).
Math.randomReturns a random number between 0 and 1.

Random

The random() method is used to return a random number in the range of 0.0 = < math random < 1.0.

common method

methoddescribe
protected int next(int bits)Generate the next pseudo-random number.
boolean nextBoolean()Returns the next pseudo-random number, which is a uniformly distributed boolean value taken from this random number generator sequence.
void nextBytes(byte[] bytes)Generate random bytes and place them in the byte array provided by the user.
double nextDouble()Returns the next pseudo-random number, which is a double value evenly distributed between 0.0 and 1.0 taken from this random number generator sequence.
float nextFloat()Returns the next pseudo-random number, which is the float value evenly distributed between 0.0 and 1.0 taken from this random number generator sequence.
double nextGaussian()Returns the next pseudo-random number, which is a Gaussian ("normal") distributed double value taken from this random number generator sequence, with an average of 0.0 and a standard deviation of 1.0.
int nextInt()Returns the next pseudo-random number, which is a uniformly distributed int value in the sequence of this random number generator.
int nextInt(int n)Returns a pseudo-random number that is an int value taken from this random number generator sequence and evenly distributed between (including) and the specified value (excluding).
long nextLong()Returns the next pseudo-random number, which is a uniformly distributed long value taken from this random number generator sequence.
void setSeed(long seed)Seed this random number generator with a single long seed.
import java.util.Random;

class Test {
    public static void main(String[] args) {
        System.out.println(Math.random()); // 0.6456063107220328
        System.out.println(Math.random()); // 0.579336669972285

        Random rand = new Random();
        int i = rand.nextInt(100);
        System.out.println(i); // Generate an integer with a random number of 0-100, excluding 100
    }
}

Date

java. The util package provides a Date class to encapsulate the current Date and time. The Date class provides two constructors to instantiate a Date object.

common method

methoddescribe
boolean after(Date date)If the Date object calling this method returns true after the specified Date, otherwise it returns false.
boolean before(Date date)If the Date object calling this method returns true before the specified Date, otherwise it returns false.
int compareTo(Date date)Compare the Date object when this method is called with the specified Date. Returns 0 when the two are equal. The calling object returns a negative number before the specified Date. The calling object returns a positive number after the specified Date.
int compareTo(Object obj)If obj is of type Date, the operation is equivalent to compareTo(Date). Otherwise, it throws ClassCastException.
long getTime( )Returns the number of milliseconds represented by this Date object since January 1, 1970, 00:00:00 GMT.
oid setTime(long time)Set the time and date in milliseconds since January 1, 1970, 00:00:00 GMT.
import java.text.SimpleDateFormat;
import java.util.Date;

class Test {
    public static void main(String[] args) {

        Date date = new Date();

        System.out.println(date.toString()); // Sat Jul 24 14:44:45 CST 2021

        long time1 = date.getTime();
        long time2 = date.getTime();
        System.out.println(time1 == time2); // true

        // SimpleDateFormat format format time
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.println(ft.format(date)); // 2021-07-24 02:46:37
    }
}

Calendar

Calendar class is an abstract class. It implements the objects of specific subclasses in actual use. The process of creating objects is transparent to programmers. You only need to use getInstance method to create objects.

constant value

constantdescribe
Calendar.YEARparticular year
Calendar.MONTHmonth
Calendar.DATEdate
Calendar.DAY_OF_MONTHDate has exactly the same meaning as the field above
Calendar.HOUR12 hour system
Calendar.HOUR_OF_DAY24-hour system
Calendar.MINUTEminute
Calendar.SECONDsecond
Calendar.DAY_OF_WEEKWhat day is today?
import java.util.Calendar;

class Test {
    public static void main(String[] args) {

        Calendar c = Calendar.getInstance();

        // Year of acquisition
        int year = c.get(Calendar.YEAR);
        System.out.println(year); // 2021

        // Get month
        int month = c.get(Calendar.MONTH) + 1;
        System.out.println(month); // 7

        // Date obtained
        int date = c.get(Calendar.DATE);
        System.out.println(date); // 24

        // Get hours
        int hour = c.get(Calendar.HOUR_OF_DAY);
        System.out.println(hour); // 14

        // Get minutes
        int minute = c.get(Calendar.MINUTE);
        System.out.println(minute); // 57

        // Get seconds
        int second = c.get(Calendar.SECOND);
        System.out.println(second); // 47

        // Get day of week
        int day = c.get(Calendar.DAY_OF_WEEK);
        System.out.println(day); // 7
    }
}

Topics: Java JavaSE