[13] Some common problems in Java SE

table of Contents

One, exception handling

Two, comparable and comparator

1. Realize Comparable:

2. Implement the Comparator interface:

Three, Java compile time and runtime

Four, hashCode() and equals() methods

Five, finalize method

Six, object-oriented, interface-oriented programming

七、String、StringBuffer、StringBuilder


One, exception handling

Error

It is an error that the program cannot handle, and it indicates a problem with the JVM when the code is running, such as OOM.

Exception

It is an exception that the program can handle. Its subclass RuntimeExcption represents runtime exceptions. Exceptions other than runtime exceptions are all non-runtime exceptions.

unchecked exception

Also called runtime exception, the compiler does not require exception handling, which is determined by the programmer, such as NullPointerException, IndexOutOfBoundsExcption.

checked exception (checked exception, compiled exception)

Also known as non-runtime exceptions (exceptions other than runtime exceptions are non-runtime exceptions), the compiler forces the programmer to deal with it, otherwise the compilation will not pass, such as common IOException and SQLException.

Two, comparable and comparator

Comparable is the internal comparator, written in the class

Comparator is an external comparator, which is written separately from the comparison class, and the coupling is low. You can override the compareTo method in a class that implements the comparable interface.

The comparator is used in the following two situations:

1. An object does not support comparing itself with itself (does not implement the Comparable interface), but wants to compare two objects

2. An object implements the Comparable interface, but the developer believes that the comparison method in the compareTo method is not the kind of comparison method they want (rewrite the compareTo method that has been rewritten, and override the compareTo method that implements the comparable interface)

 

1. Realize Comparable:

package testJavaInterfaceAndMethod;

public class Person implements  Comparable<Person>{//本类实现Comparable接口,内比较器方法只需要一个参数

    private int age;

    private String name;

    public Person() {

        

    }

    public Person(int age, String name) {

        super();

        this.age = age;

        this.name = name;

    }

    public int getAge() {

        return age;

    }

    public void setAge(int age) {

        this.age = age;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    @Override

    public int compareTo(Person o) {

        return this.getAge()-o.getAge();

    }

    @Override

    public String toString() {

        return "Person [age=" + age + ", name="  + name + "]";

    }

}

2. Implement the Comparator interface:

package testJavaInterfaceAndMethod;

importjava.util.Comparator;

public class PersonComparator implements  Comparator<Person>{//外比较器,方法需要两个参数

//为什么不用重写Comparator中的所有抽象方法

    @Override

    public int compare(Person o1, Person o2) {

        return o2.getAge()-o1.getAge();//注意这里的顺序和实现Comparable接口的compareTo方法属性不一致。

    }

}

test:

package testJavaInterfaceAndMethod;

import java.util.Arrays;

import org.junit.Test;

public class Main {

    @Test

    public void testComparable() {

        Person person1 = new Person(22,"dhl");

        Person person2 = new Person(21,"pj");

        Person[] persons = {person1,person2};

        for (int i = 0; i < persons.length; i++)  {

            System.out.println(persons[i]);

        }

        Arrays.sort(persons,new  PersonComparator());//使用外比较器的方法

        for (int i = 0; i < persons.length; i++)  {

            System.out.println(persons[i]);

        }

    }

}

result:

Person [age=22, name=dhl]

Person [age=21, name=pj]

Person [age=22, name=dhl]

Person [age=21, name=pj]

Use internal comparator and external comparator at the same time, external comparator takes precedence

Three, Java compile time and runtime

Compile time: compile the source code into bytecode that can be recognized by the JVM

Runtime: Load the bytecode into the memory to run.

Example:

public class ConstantFolding {

static final int number1 = 5;

static final int number2 = 6;

static int number3 = 5;

static int number4= 6;

public static void main(String[ ] args) {

int product1 = number1 * number2; //line A

int product2 = number3 * number4; //line B

}

}

Analysis:

lineA 是在编译期间计算的。

lineB 是在运行期间计算的。

Constant folding is an optimization technique used by the Java compiler . Since the value of final variables will not change, they can be optimized.

 

Method overloading: This happens at compile time. Method overloading is also called compile-time polymorphism , because the compiler can choose which method to use based on the type of the parameter.

Example:

public class {

public static void evaluate(String param1); // method #1

public static void evaluate(int param1); // method #2

}

 

Method coverage: This happens at runtime. Method overloading is called runtime polymorphism, because the compiler does not know and cannot know which method to call at compile time. The JVM will make a decision while the code is running.

Example:

public class A {

public int compute(int input) { //method #3

return 3 * input;

}

}

public class B extends A {

@Override

public int compute(int input) { //method #4

return 4 * input;

}

}

The compute(..) method in subclass B overrides the compute(..) method of the parent class. If the compiler encounters the following code:

public int evaluate(A reference, int arg2) {

int result = reference.compute(arg2);

}

The compiler has no way of knowing whether the type of the parameter reference passed in is A or B. Therefore, it can only be decided to call method #3 or method #4 at runtime based on the type of object assigned to the input variable "reference" (for example, an instance of A or B)

 

Generic (also known as type checking): This happens at compile time. The compiler is responsible for checking the correctness of the types in the program, and then translating or rewriting the code that uses the generics into non-generic codes that can be executed on the current JVM. This technique is called "type erasure".

In other words, the compiler will erase all type information in angle brackets to ensure compatibility with JRE version 1.4.0 or earlier.

Example:

Before compilation:

List<Person> myList = new ArrayList(10);

After compilation: 

List myList = new ArrayList(10);

Four, hashCode() and equals() methods

Java's regulations: if two objects are equals equals, then hashCode must be equal (the equals and hashCode methods here refer to the methods in the Object class that are not overridden, and the equals() method that is not overridden compares the address of the object ( Use == to compare directly).

That is to say, if two objects have the same address, then their hashCode must be the same, and the address is different, then it is not necessarily), but the hashCode is equal, the object is not necessarily equal, the hashCode is not equal, then the object must not be equal.

1. The main purpose of the hashCode() method is to improve the query efficiency in the storage of the hash structure.

If there is no hashCode method, in order to avoid adding the same key in the HashMap, then equals comparisons are needed as many elements as there are. However, if there is a hashCode method, the corresponding hash bucket will be found according to the hashCode value first, and then Perform equals comparison, reducing the number of comparisons.

2. The condition for judging the equality of two objects in the set collection, in fact, whether it is to store data in the set collection or fetch data from the set collection, including controlling uniqueness, etc., are all judged by this condition. The conditions are as follows:

    First judge whether the hashCodes of the two objects are equal, if they are not equal, the two objects are considered to be unequal, and it is done. If they are equal, it will be judged whether the equals() of the two objects are equal, if they are not equal, the two objects are considered to be unequal, and if they are equal, the two objects are considered equal.

So to ensure the uniqueness of the elements in the set:

1. The hashCode method should be rewritten after the equals method is rewritten (do not rewrite the hashCode method, equals but the hashCode is different, it will be repeated at this time)

2. Only rewrite the hashCode method without rewriting the equals method: the hashCode will be different, but the object may be equals, or there will be element duplication.

Five, finalize method

Finalize is defined in the java.lang.Object class. This method is called before the gc is started and the object is recycled. In fact, gc can recycle most of the objects, so programmers are generally not required to implement finalize. Resources need to be released when the object is recycled, and the finalize() method can be implemented at this time.

The finalize() method of an object can only be called once , and the finalize() method being called does not mean that gc will immediately reclaim the object , so it is possible that after finalize() is called, the object will not be reclaimed, and it will be reclaimed. When the object is used, the finalize() method will not be called because it has been called before, which causes problems. In addition, the finalize() method will ignore the exception, that is, if an exception occurs in the finalize code, the exception will be ignored. It is recommended not to actively use the finalize() method, which is different from the destructor (the destructor is automatically called when the use range of the variable is exceeded, and the variable is destroyed after the destructor is called).

Six, object-oriented, interface-oriented programming

Everything is an object, and every object in real life belongs to a class of things, and every individual is an instance of a class of things.

Object-oriented has three major characteristics, encapsulation, inheritance and polymorphism.

1. Encapsulation is to abstract the attributes and behaviors of a class of things into a class, privatize the attributes and make the behavior public, improve the privacy of the data, and make the code modular. Doing so makes the code more reusable.

2. Inheritance is to further abstract the properties and behaviors shared by a class of things into a parent class, and each subclass is a special parent class-with the behavior and properties of the parent class, and also has its own unique behavior and properties. This expands the existing code block and further improves the reusability of the code.

3. If encapsulation and inheritance are for code reuse, polymorphism is for interface reuse. A major function of polymorphism is to decoupling-in order to remove the coupling degree of parent-child class inheritance. If we say that the relationship between parent and child class in inheritance is IS-A, then the relationship between interface and implementation class is HAS-A. Simply put, polymorphism is to allow parent class references (or interfaces) to point to subclass (or implementation class) objects. Many design patterns are based on object-oriented polymorphism design.

To sum up, if encapsulation and inheritance are the basis of object-oriented, then polymorphism is the essence of object-oriented theory. To master polymorphism, you must first understand the interface. Only by fully understanding the interface can you better apply polymorphism.

Interface-oriented programming: interface is also a kind of specification! Interface-oriented programming is similar to complying with company regulations in reality! This enhances the flexibility and maintainability of the system and reduces the impact! Realize what is often said in the project: high cohesion, low coupling!

七、String、StringBuffer、StringBuilder

String string constant; StringBuffer string variable (thread-safe); StringBuilder string variable (non-thread-safe)

String S1 = “This is only a” + “ simple” + “ test”;

In fact: String S1 = "This is only a simple test"

When the string changes frequently, the speed: StringBuilder>StringBuffer>String

Guess you like

Origin blog.csdn.net/Jack_PJ/article/details/88038129