Basic Knowledge of Java
Java == vs. Equals and hashCode
For the relational operator ==
- If the operand is of a primitive data type, the relational operator determines whether the left and right operands are equal
- If the operand type is a reference data type, the relational operator determines whether the memory addresses of the left and right operands are the same. That is, if true is returned, the operator must operate on the same object.
For using the equals method, the internal implementation is divided into three steps:
- First compare whether the references are the same (whether they are the same object),
- Then determine whether the type is consistent (whether it is the same type),
- Finally, compare whether the content is consistent
The equals method is implemented for all built-in Classes in Java, especially wrapper classes such as Integer and Double. The equals method is implemented as in String below
// String.java
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while(n-- ! =0) {
if(v1[i] ! = v2[i])return false;
i++;
}
return true; }}return false;
}
Copy the code
Hashcode is used by the system to quickly retrieve objects
The equals method is intended to determine whether the objects referenced are consistent
When you override the equals and HashCode methods, the member variables used in the equals and HashCode methods must also be used in the HashCode method, except that the former is used as a comparison item and the latter is used as an information item to generate the summary, essentially using the same data to ensure consistency
reference
- Java ==, equals, hashCode
- Effective Java article 8,9
The number of bytes of int, char, and long
The number of bytes occupied by Java base types
- 1 byte: byte, Boolean
- 2 bytes: short, char
- 4 bytes: int, float
- 8 bytes: long, double
Note: 1 byte =8 bits
- Related articles
The difference between int and integer
- Integer is a wrapper class for int, which is a basic data type in Java
- Integer variables must be instantiated before they can be used, whereas int variables do not
- An Integer is actually a reference to an object, and when you new an Integer, you’re actually generating a pointer to that object. Int stores data values directly
- The default value of Integer is null, and the default value of int is 0
reference
- Related articles
Understanding Java polymorphism
Polymorphism refers to that when a method of a parent class is overwritten by a child class, it can produce its own functional behavior. The same operation acting on different objects can have different interpretations and produce different execution results.
Three necessary conditions for polymorphism:
- Inherits the parent class.
- Override the method of the parent class.
- A reference to a parent class points to a subclass object
Further understanding can then be made by combining Richter’s substitution rule
Richter’s Substitution rule —- All references to a base class must be able to transparently use objects from its subclasses
- A subclass must fully implement the methods of its parent class
Notice The parent class or interface must be used when invoking other classes in a class. If the parent class or interface cannot be used, the design of the class violates THE LSP principle
Notice If the subclass cannot completely implement the methods of the parent class, or some methods of the parent class have “distortion” in the subclass, it is recommended to disconnect the parent-child inheritance relationship and use dependency, aggregation, and composition relationships instead of inheritance
- Subclasses can have their own personalities
- The input parameters can be amplified when overriding or implementing methods of the parent class
- The output can be reduced when overwriting or implementing methods of the parent class
In the project, when using the Richter substitution principle, try to avoid the “personality” of the subclass, once the subclass has “personality”, the relationship between the subclass and the parent class is difficult to reconcile, use the subclass as the parent class, the “personality” of the subclass will be erased — a bit of a pity; Using subclasses as a separate business makes coupling between code confusing — there is no standard for class substitution
StringBuffer StringBuilder
Stringbuffers, like Strings, are used to store strings, but because of the way they are implemented internally, they are used in different scopes. A StringBuffer does not generate a new String object if it is modified while processing a String. So it’s better than String in terms of memory usage
StringBuilder is also a mutable string object, which differs from StringBuffer in that it is thread-safe and is generally faster than StringBuffer because of this
Concatenation of String strings is parsed by the JVM into Concatenation of StringBuilder objects, in which case String is faster than StringBuffer
STR += “b” equals STR = new StringBuilder(STR).appEnd (” b “).toString();
- Related articles
Explain inner classes in detail
Inner classes complete multiple inheritance solutions
The most interesting reason for using inner classes is that each inner class can inherit an implementation independently, so it doesn’t matter whether the enclosing class already inherits an implementation
Multiple inheritance is achieved using inner classes
- An inner class can have multiple instances, each of which has its own state information and is independent of the information of other peripheral objects.
- Within a single enclosing class, you can have multiple inner classes implement the same interface in different ways, or inherit from the same class.
- The time at which the inner class object is created does not depend on the creation of the outer class object.
- The inner class does not have a confusing “IS-A” relationship; it is a separate entity.
- The inner class provides better encapsulation and is not accessible by any other class except the enclosing class.
When we create an inner class object of a enclosing class, the inner class object must capture a reference to that enclosing class object, and whenever we access a member of the enclosing class, we use that reference to select the member of the enclosing class
Member inner class
There are two things to note in member inner classes,
- There cannot be any static variables or methods in a member inner class
- The member inner class is attached to the enclosing class, so the inner class can only be created if the enclosing class is created first
Static inner class
One of the biggest differences between a static inner class and a non-static inner class is that a non-static inner class implicitly stores a reference to the enclosing enclosing it after compilation, whereas a static inner class does not. The absence of this reference means:
- Its creation does not depend on the enclosing class.
- It cannot use non-static member variables and methods of any enclosing class.
reference
- Related articles
Why can anonymous inner classes in Java only access final modified external variables?
Anonymous inner class usage
public class TryUsingAnonymousClass {
public void useMyInterface(a) {
final Integer number = 123;
System.out.println(number);
MyInterface myInterface = new MyInterface() {
@Override
public void doSomething(a) { System.out.println(number); }}; myInterface.doSomething(); System.out.println(number); }}Copy the code
The compiled result
class TryUsingAnonymousClassThe $1implements MyInterface {
private final TryUsingAnonymousClass this$0;
private final Integer paramInteger;
TryUsingAnonymousClass$1(TryUsingAnonymousClass this$0, Integer paramInteger) {
this.this$0 = this$0;
this.paramInteger = paramInteger;
}
public void doSomething(a) {
System.out.println(this.paramInteger); }}Copy the code
Because anonymous inner classes are eventually compiled into a single class, variables used by the class are passed to the class as constructor arguments, such as: Integer paramInteger. If the variable is not defined as final, paramInteger can be modified in the anonymous inner class, resulting in inconsistency with external paramInteger. To avoid this inconsistency, Because Java dictates that anonymous inner classes can access only final modified external variables
- Anonymous inner class related articles
- Java face test set
The difference between abstract classes and interfaces
- Default method implementations Abstract classes can have default method implementations that are completely abstract. Interface there is no implementation of a method at all
- Implementing abstract classes inherits abstract classes using the extends keyword. If a subclass is not abstract, it needs to provide implementations of all methods declared in the abstract class. Subclasses implement the interface using the keyword implements. It needs to provide implementations of all declared methods in the interface.
- Abstract classes can have constructors, but interfaces cannot
- Abstract methods can have public, protected, and default modifiers. The default modifier for interface methods is public. You may not use other modifiers.
- Abstract classes represent an inheritance relationship in the Java language. A subclass can have only one parent class, but can have multiple interfaces.
- Abstract methods are faster than interfaces, which are slightly slower because it takes time to find methods implemented in classes.
- If you add a new method to an abstract class, you can provide it with a default implementation. So you don’t need to change your current code. If you add methods to an interface, you must change the class that implements the interface
reference
- Related articles
The difference between extends and super in generics
- Related articles
A static method of a parent class can be overridden by a subclass
Static methods and static member variables can be inherited, but cannot be overridden. It is hidden from subclasses, so static methods cannot be polymorphic
- Related articles
The difference between processes and threads
The main difference between processes and threads is that they are different ways of managing operating system resources. Processes have independent address Spaces, a crash of one process in protected mode does not affect other processes, and threads are just different execution paths within a process. Thread has its own stack and local variables, but there is no separate address space between threads, a thread dead is equal to the whole process dead, so multi-process procedures than multithreaded procedures robust, but in the process switch, the cost of resources is larger, the efficiency is poor. However, for concurrent operations that require simultaneous and variable sharing, only threads, not processes, can be used.
- Related articles
- Related articles
Final, finally, Finalize
-
Final is used to declare properties, methods, and classes, indicating that properties are immutable, methods are not overridden, and classes are not inherited, respectively.
-
Finally is part of the exception handling statement structure and means always execute.
-
Finalize is a method of Object class. When garbage collector executes, Finalize will call the method of the Object to be collected, and can overwrite the method to provide other resource collection during garbage collection, such as closing files. The JVM does not guarantee that this method will always be called.
reference
- Related articles
Difference between Parcelable and Serializable
Serializable is a serialization interface in Java, which is simple but expensive to use, with serialization and deserialization processes requiring a lot of I/O operations. Parcelable is the serialization method in Android, so it is more suitable for The Android platform. The disadvantage of Parcelable is that it is a little bit troublesome to use, but it is very efficient. It is the recommended serialization method in Android, so we prefer Parcelable. Parcelable is mainly used for memory serialization. It is also possible to serialize objects to a storage device using Parcelable or to transfer objects over a network after serialization, but this process is slightly more complicated, so Serializable is recommended in both cases.
reference
- Related articles
- Android development art exploration
Why can’t a non-static inner class have static attributes
- Related articles
Talk about your understanding of Kotlin
It varies from person to person, please sort out the answers by yourself
The method and principle of converting String to INTEGER
Integer a = 2;
private void test(a) {
String s1 = a.toString(); / / way
String s2 = Integer.toString(a); 2 / / way
String s3 = String.valueOf(a); 3 / / way
}
Copy the code
Method one source:
public String toString(a) {
return toString(value);
}
public static String toString(int i) {
if (i == Integer.MIN_VALUE)
return "2147483648";
int size = (i < 0)? stringSize(-i) +1 : stringSize(i);
char[] buf = new char[size];
getChars(i, size, buf);
return new String(buf, true);
}
Copy the code
You can see that method one ends up calling method two
The toString() method converts integers (including 0) to a string, but an Integer that is null will result in a null-pointer exception
Method three source code:
public static String valueOf(Object obj) {
return (obj == null)?"null" : obj.toString();
}
public String toString(a) {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Copy the code
You can see that when Integer is null, the returned String is the String “null” instead of NULL