This is the 23rd day of my participation in the August More Text Challenge.More challenges in August

The article directories

  • API
  • java.lang.Object
  • java.lang.String

API

API, English full name Application Programming Interface, translated as Application Programming Interface. Are predefined functions designed to provide applications and developers with the ability to access a set of routines based on a piece of software or hardware without having to access the source code or understand the details of the inner workings.

Java’s core API is very large, which makes it very convenient for developers. An API is a library of classes that have been written and can be called directly. Java has a very large API, which has some class library is we must have to master, only master some core Java API, we can better use Java.

The apis commonly used in our current learning phase are as follows:

Java.lang. Object lang-language language package. The java.lang package does not require the import keyword to be introduced in the program as other packages do. The system will load automatically, so we can directly access all the classes in it. Java.lang.String java.lang.StringBuilder Java.lang.StringBuffer Regular expression java.util.regex.Pattern java.util.regex.matcher The base type wrapper class java.math.BigDecimal java.math.bigINTEGER java.text.DecimalFormat java.lang.Math Date-related type java.util.date java.text.SimpleDateFormat java.util.Calendar java.util.GregorianCalendar

The following chapter focuses on java.lang.Object and java.lang.String

java.lang.Object

The Object class is the top-level parent of all classes in Java. If a class does not inherit from another class, the default extends Object, omitting extends Object.

class A extends Object{} we just have to writeclass A {}Copy the code

methods

1, the toString ()

The toString method of the Object class returns a string consisting of the class name, the marker “@”, and an unsigned hexadecimal representation of the Object’s hash code.

For example, we have a Point class that contains coordinate points x and y

public class Point {
    int x;
    int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y; }}Copy the code

We create a Point instance and Log the result of toString() :

Point point = new Point(3.4);
Log.d("TTT", point.toString());
// Output the result
D/TTT: com.example.testapplication.Point@640983e
Copy the code

Format: package name@memory address. That’s not what we want, so this method is usually rewritten

public class Point {... (Same content as above)public String toString(a) {
        return "(" + x + "," + y + ")"; }}Copy the code

Run the program again to see the print

D/TTT: (3.4)
Copy the code

Equals (Object obj) equals(Object obj) equals(Object obj)

Point point1 = new Point(3.4);
Point point2 = new Point(3.4);
Log.d("TTT"."" + point1.equals(point2));
Copy the code

The output is false because the memory address is different. If desired, you can override this method in a subclass to compare objects’ attributes for equality.

public class Point {... (Same content as above)@Override
    public boolean equals(Object obj) {
        if (obj == null) return false;
        if (obj == this) return true;
        if(! (objinstanceof Point)) return false;
        Point p = (Point) obj;
        return
                this.x == p.x && this.y == p.y; }}Copy the code
Point a = new Point(3.4);
Point b = new Point(3.4);

Log.d("TTT"."" + (a == b));/ / output is false
Log.d("TTT"."" + (a.equals(b)));/ / output true
Copy the code

Object’s hashCode() method is used for hash lookups to reduce the number of times equals is used in lookups. Overriding the equals method usually overrides the hashCode method.

The hashCode () method returns an integer value representing the hash value of the object, using the memory address value as the default hash value

If desired, you can override this method in a subclass, using the attribute data to compute the resulting hash value.

Point point = new Point(3.4);
Log.d("TTT"."" + point.hashCode());/ / output 104896574
Copy the code

java.lang.String

Introducing the String class is also a class under the java.lang package. A String String is actually a final char array.

String is a constant class declared with final, and cannot be inherited by any class. 2. The main member of the String class value is a final char[] array. Fields modified by final are immutable after creation. Some of the methods in this class appear to change the string, but inside they create a new string. That is, these operations are not performed on the original string, but a new string object is generated, after these operations, the original string is not changed.

String creation

1, the first method, through the “literal” form of direct assignment

String a = "hello";
Copy the code

2. The second method is to create an object by calling the constructor with the new keyword

char[] a = {'h'.'e'.'l'.'l'.'o'};
String s = new String(a);
Copy the code

The difference between the two can be understood through an example:

String a = "hello";
String b = new String(new char[] {'h'.'e'.'l'.'l'.'o'});
String c = "hello";
String d = new String(new char[] {'h'.'e'.'l'.'l'.'o'});
Log.d("TTT"."" + (a == b));//false
Log.d("TTT"."" + (a == c));//ture
Log.d("TTT"."" + (b == d));//false
Copy the code

The first method, when assigning a literal directly, creates a new instance in the string constant pool (explained below), and when using the same literal again, accesses the existing object in the constant pool without creating a new object. A creates “Hello” in the string constant pool, and c checks for “Hello” objects in the string constant pool during creation.

Object generation via the new keyword is done in the heap, and object generation in the heap does not detect whether the object already exists. So if you create an object with new, you’re going to create a different object, even if the contents of the string are the same.

In addition, String is a reference type; use == to determine if it is the same object. Operations performed with symbols are done in stack memory, such as =, ==, etc. So the comparison is whether the reference address or memory address is equal.

immutable

String is essentially data stored in an array in memory. The length of the array is immutable, and the created String object is immutable, but the variable is variable. For example String a = “hello”; The value of s can be changed, but the string “hello” is immutable.

Because string is immutability, repeatedly create string is a very memory consumed, so an area specifically designated in the memory to store all sorts of constants, and in constant in this region has a special area to hold the string constants, is called a string constant pool, it has a feature is, the string is the only one.

Such as:

String s1 = "hello";
String s2 = "hello";
Log.d("TTT"."" + (s1 == s2));//true
Copy the code

When s1 is created, the string constant pool has 1 “hello”. When S2 is created, it is no longer created in the constant pool because it is also “hello”. S2 points directly to the previously created constant.

Creating with the keyword new is different.

String s3 = new String("hello");
String s4 = new String("hello");
Log.d("TTT"."" + (s3 == s4));//false
Copy the code

Whenever you see an object created by new, it must be in the heap. New means to request a new space to store it.

We can expand on that.

String s5 = "he" + "llo";
Log.d("TTT"."" + (s1 == s5));//true
Copy the code

S5 is the sum of two constants, constant + constant = constant. This process is done during compilation without waiting for the program to run, so when the program runs, s5 equals “hello”, so s1 == s5 returns true

String s6 = "he";
s6 += "llo";
Log.d("TTT"."" + (s1 == s6));//false
Copy the code

S6 is a variable + a constant = a variable. For a program, variables are only known at runtime, and there is absolutely no way that the resulting value is in the constant pool. Therefore, s6 produces values in heap memory, while S1 is in the constant pool, so s1 == s6 returns false.

String s7 = s1;
Log.d("TTT"."" + (s1 == s7));
Copy the code

S7 is an assignment. Assign the reference address of s1 directly. So s1 == s7 returns true

StringBuilder and StringBuffer are necessary

In the last article, we looked at StringBuilder and StringBuffer. Why do we need StringBuilder and StringBuffer classes when we already have String classes in Java? The reason for this is that string concatenation is inefficient because strings are immutable once created, which is reflected in the fact that a new instance is created for each connection.

In the previous chapter, we used StringBuilder to concatenate the letters A-Z 100,000 times in 22 milliseconds. Let’s test the time used with + concatenation.

String s0 = "abcdefghigklmnopqrstuvwxyz";
long t = System.currentTimeMillis();
String b = "";
for (int i = 0; i < 1000; i++) {
	b += s0;
}
System.out.println(System.currentTimeMillis() - t);
Copy the code

The result was executed in 73 milliseconds. It’s significantly slower than StringBuilder.



StringBuffer is much more efficient than String. String += creates a new String every time and allocates new memory every time. A StringBuffer trades space for time, starting with a large space and concatenating the string at the end of each concatenation.

For high frequency String concatenation, more than 5 times, StringBuffer and StringBuilder should be used, not String.

In the previous chapter, StringBuffer is safe, StringBuilder is not. The so-called security and insecurity is when multiple threads work on the same data.

For example, if StringBuilder = “ABC” is used, and three threads are changing its value, all three threads may be running at the same point in time, then this value is out of control. StringBuffer guarantees that. When you don’t care about multithreading, StringBuilder is fine.

For other articles on strings, see my articles on String-related Methods, StringBuilder, and StringBuffer