java.lang package common classes
java.lang Classes in the package are automatically imported and usually do not need to be written when used import Statement.
Object class
Object is the root class of the Java class hierarchy and all classes inherit it directly or indirectly.
toString() method
toString() Returns the string representation of the object. The default format is usually defined by the class name,@ and the hexadecimal form of the hash code, but it is not a reliable memory address.
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}equals() method
Object.equals() Default and == The effect is the same, comparing whether two references point to the same object. Subclasses can override this and compare object content instead.
rewrite equals() Sometimes it is also rewritten hashCode(), ensure that objects with equal content have the same hash code.
hashCode() method
hashCode() Returns an integer hash value, commonly used in HashMap、HashSet Wait for the hash structure. The same hash code does not mean that objects must be equal, but equals() Equal objects must have the same hash code.
clone() method
clone() Used to copy objects. called directly Object.clone() Class of typically needs to implement Cloneable Interface, otherwise it will throw CloneNotSupportedException。The default clone is a shallow copy, and the reference field may still point to the same object.
finalize() method
finalize() There is no guarantee when it will be executed, nor is it suitable to release resources such as files and network connections. should be used try-with-resources Or explicitly turn off methods to manage resources, do not rely on finalize()。
wrapper class
All eight basic types have corresponding packaging categories.
| basic types | wrapper class |
|---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
char | Character |
float | Float |
double | Double |
boolean | Boolean |
Wrapper classes encapsulate basic type values into objects for easy use in scenarios such as generic collections that only accept reference types.
Integer Common methods
recommended Integer.valueOf() created or retrieved Integer objects, using Integer.parseInt() Convert a string to int。
Integer value1 = Integer.valueOf(3);
Integer value2 = Integer.valueOf("3");
int number1 = value1.intValue();
int number2 = Integer.parseInt("100");Integer.valueOf() Cache objects that reuse some commonly used values. The Java specification requires at least caching -128 to 127, a larger cache range may be determined by JVM configuration.
Integer value1 = Integer.valueOf(3);
Integer value2 = Integer.valueOf(3);
System.out.println(value1 == value2); // 通常为 true
Integer value3 = Integer.valueOf(300);
Integer value4 = Integer.valueOf(300);
System.out.println(value3 == value4); // 不应依赖该结果When comparing the numerical content of packaging categories, use the equals(), do not use == Determine the content of the object.
Automatic boxing and automatic unpacking
JDK 5 begins to support automatic boxing and automatic unpacking.
Integer value = 3; // 自动装箱,相当于 Integer.valueOf(3)
int number = value; // 自动拆箱,相当于 value.intValue()If the packaging class is referenced as null, will throw NullPointerException。
Integer value = null;
// int number = value; // 运行时抛出 NullPointerExceptionString class
String Represents an immutable sequence of characters. After a string object is created, its character content cannot be modified; what appears to be modifying a string will actually return a new string.
String text = "abcdefg";
String result = text.replace("bcd", "BCD");
System.out.println(text); // abcdefg
System.out.println(result); // aBCDefgString realized CharSequence Interface, therefore requires CharSequence The position of the parameter can be passed in a string.
Internal storage of String
Different JDK versions have different implementations. Java 8’s String mainly used char[] Saving content; newer JDK usage byte[] Use the encoding mark to achieve a compact string. learn and use String APIs should not rely on specific internal array types.
String constant pool
String literals are put into the string constants pool, and the same literals are usually reused on the same object. use new String() A new object is explicitly created.
String s1 = "ab";
String s2 = "ab";
System.out.println(s1 == s2); // true
String s3 = new String("ab");
String s4 = new String("ab");
System.out.println(s3 == s4); // false
System.out.println(s3.equals(s4)); // trueString constant expressions that can be determined during compilation time are collapsed.
String s1 = "ab";
String s2 = "a" + "b";
System.out.println(s1 == s2); // trueSplices that contain variables usually produce result objects during run time and should not be used == Compare string content.
String Common methods
Get length and characters
String text = "abcdefg";
System.out.println(text.length());
System.out.println(text.charAt(2));compare strings
equals() Compare whether the content is equal,compareTo() Compare in dictionary order.compareTo() Returns negative, zero or positive numbers, there is no guarantee that only returns -1、0、1。
System.out.println("abc".equals("abc"));
System.out.println("abc".compareTo("abd"));Find and judge
String text = "abcdefgabc";
System.out.println(text.contains("cde"));
System.out.println(text.startsWith("abc"));
System.out.println(text.endsWith("abc"));
System.out.println(text.indexOf("abc"));
System.out.println(text.lastIndexOf("abc"));When the specified content cannot be found,indexOf() and lastIndexOf() return -1。
intercept string
substring() The ending index of is not included in the results.
String text = "abcdefg";
System.out.println(text.substring(2));
System.out.println(text.substring(2, 5)); // cdeReplacement, splitting and case conversion
String text = "abcbc";
System.out.println(text.replace("bc", "BC"));
System.out.println(Arrays.toString(text.split("b")));
System.out.println(text.toUpperCase());
System.out.println(text.toLowerCase());
System.out.println(" Java ".trim());split() The argument to is a regular expression. When splitting special characters such as dots and vertical lines, you need to escape them according to regular expression rules.
Strings and byte arrays
Character sets should be clearly specified when encoding and decoding.
String text = "你好";
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
String result = new String(bytes, StandardCharsets.UTF_8);
System.out.println(text.equals(result));StringBuffer class
StringBuffer Is a sequence of characters whose content is variable. It maintains an expandable buffer internally, and usually does not need to add, insert or delete content such as String Create a large number of intermediate objects repeatedly like splicing.
StringBuffer buffer = new StringBuffer("a");
for (int i = 0; i < 10_000; i++) {
buffer.append('a');
}
String result = buffer.toString();Constructors usually reserve extra capacity based on the initial string length. When the buffer space is insufficient, it will be automatically expanded, and the specific expansion strategy belongs to the implementation details.
Common StringBuffer Methods
StringBuffer buffer = new StringBuffer("Java");
buffer.append(" SE");
buffer.insert(4, " 8");
buffer.delete(4, 6);
buffer.reverse();
System.out.println(buffer);Common methods include append()、insert()、delete()、replace() and reverse()。
StringBuilder class
StringBuilder with StringBuffer Provides similar APIs and also belongs to variable character sequences.
StringBufferThe main method with synchronization control is suitable for scenarios where multiple threads share the same instance and modify it at the same time.StringBuilderWithout this synchronization guarantee, the overhead is generally lower in single-threaded scenarios.
Most local string splicing scenarios are preferred StringBuilder。Thread safety cannot be judged solely based on the class name, but also based on whether the object is shared by multiple threads and whether the overall operation is atomic.
If you enjoyed this, leave a comment~