Summary of Java problems (commonly used APIs and collections):

Table of contents

1.String s=new String("xyz") How many objects are created?

2. The switch statement in Java can only be int, enumeration type?

3. The difference between Overload and Override. Can an Overloaded method change the type of the return value?

4. Wrong question 1: The one that does not generate compilation errors is:

5. Wrong question 2: There is a compilation error

6. Why does Hashse have to rewrite the hashCode and equals methods in the object when storing custom type elements to ensure that the elements are unique.

7. When new an object is passed to the parent class type, when the static method of the subclass is called, why is the static method of the parent class called?

1.String s=new String("xyz") How many objects are created?

Find xyz in the String pool, do not create an object, otherwise create an object.

The new keyword creates a String class object.

My own understanding and access to some information (I don’t know if it’s right, please correct me if I’m wrong).

2. Can the switch statement in Java only apply to int and enumeration types?

    2.1 Use of switch:

The switch statement is suitable for matching and judging multiple integer values ​​(including negative numbers), so as to realize conditional branch control.

If the judgment is true, find the corresponding case value and execute the corresponding code

   The difference from the if statement is:

1. The if statement is judged according to the following expression, so this judgment can be written arbitrarily.

2. The switch statement is simply a judgment of "expression == value", which is just a judgment of an integer.

    2.2 switch implementation principle:

The program is ultimately a statement. There is an instruction indicator in the CPU. The CPU loads and executes instructions according to the instruction device. When an instruction is completed, the instruction device will automatically point to the next instruction. Some instructions will modify the value of the instruction indicator to make the CPU Jump to other places to execute, this kind of instruction is called jump instruction. There are two types of jump instructions: a conditional jump statement, if the jump condition is met, then jump. The other is an unconditional jump, which directly jumps to execute the instruction.

    Correspondingly put it in the switch statement:

The switch statement is compiled into a class file. When there are few branch statements, the conditional jump statement will be used directly, and the case statement will be executed if the condition is met. When there are many branch statements, to avoid inefficiency, use the jump table-mapping table to store the address corresponding to the corresponding value. Find the jump address based on this value.

   2.3 Solution:

Short, byte, and char are all available, because they will be automatically converted to int, but long cannot, because long exceeds the range of the jump table, and the String type can be converted to the corresponding integer using hashcode.

So: Byte, Short, Character, Integer, and enumeration types supported from Java5 and String classes supported from Java7. Both apply to switch statements.

3. The difference between Overload and Override. Can an Overloaded method change the type of the return value?

Overload (overload): Overloading is a polymorphism at the method level. In the same class, as long as the method name is the same, the parameter list (parameter order, number of parameters, and parameter type) is different, which constitutes overloading.

Override (override): Override is polymorphism at the level of the parent class and the child class. Rewrite the execution statement in the subclass, and the method declaration must be the same as that of the parent class.

Overload has nothing to do with changing the return value type, it can be changed.

4. Wrong question 1:

The following options can replace //add code here in the title without generating compilation errors (AD). (choose two)

public abstract class MyClass{

public  int  constInt=5;

//add code here

public void method( ){

}

}

A

public abstract void method(int a);

B.

constInt =constInt+5;

C.

public int method( );

D.

public abstract void anotherMethod( );

analyze:

1. Method overloading only needs to be different in the parameter list (parameter number, parameter type, parameter order), and has nothing to do with the return value type and whether to add keywords such as abstract.

2. Attribute definition and assignment can be written outside the method, but other operations such as attribute operations should be written inside the method.

class MyClass {
    int[] a=new int[10];
    a[2]=a[2]+2;
    public void eat(){
        int constInt=5;
        constInt =constInt+5;
    }

    public void method( ){
    }

The layer of code outside the method will report an error, but not inside.

5. Wrong question 2:

Known classes A, B, C and interface D are defined as follows:

    public class A{…}

    public class B extends A implements D {…}

    public class C extends A {…}

    public interface D {…}

    The variables a, b, c, d are defined as follows:

    A a = new A();  B b = new B();  

    C c = new C();  D d = null;

    Then the following statement will have a compilation error (D).

A.   

  a = b;

B.   

  d = b;  

C.   

  d = (D)a;

D.   

  c = (C)b; ( a cat cannot be converted to a dog)

What we are examining is polymorphism, one of the three major characteristics. Regarding polymorphism, we need to remember these key parts:

   1. Upward transformation, downward transformation

   2. The subclass object is passed to the parent class type, which is polymorphic.

   3.instaceof keyword

In this question, objects of the same level cannot be forcibly transferred - cats cannot be converted into dogs

6. Why does Hashse have to rewrite the hashCode and equals methods in the object when storing custom type elements to ensure that the elements are unique.

 How does Hashset judge that the elements are the same?

  1. First calculate the hash value of the element through the hashcode. If there is an existing hashcode that is the same as it, then it will be regarded as the same element, and the second step will be performed. If they are not the same, it means that the elements are different and added to the collection.

  2. When the hash values ​​are the same, call the equals method to compare whether the attributes of the two elements are the same. If they are the same, no element will be added, and if they are not, they will be added to the collection.

Look at this example:

public class HashsetTest {
    public static void main(String[] args) {
        HashSet hashSet = new HashSet();
        hashSet.add(new Student("小李"));
        hashSet.add(new Student("小李"));
        int a=hashSet.size();
        System.out.println("元素个数为:"+a);
    }
}
class Student{
    int id;
    String name;
}

 Output result:

Indicates that both elements are added. why?

  Going back to how hashset judges that the elements are the same, first of all, I pass in two objects with the same attributes—the objects are the same, but the address values ​​are different. Therefore, the hashcode is different, and the judgment mechanism will return false to judge that the two are different, so that two identical objects of the same type are stored in the collection. So we have to rewrite the hashcode method and point the judgment to its attribute (name). At this time, we get the hashcode corresponding to the attribute value name, not the hashcode of the address value.

@Override
    public int hashCode() {
        return this.hash(name);
    }

Since the return is true, enter the second step to call the equals method. There is no equals method in our custom class. The equals method in the Objects class is called, and it compares the address value, so we have to rewrite equals method.

 @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Student)) return false;
        Student student = (Student) o;
        return name.equals(student.name);
    }

After rewriting, the content of the corresponding attribute is compared. Finally, it is judged whether it is the same element.

 important point:

The equals in Object compares the address of the object, and the hashcode is also calculated based on the address. After rewriting, hashcode compares attributes, and equals compares attributes.

7. When new an object is passed to the parent class type, when the static method of the subclass is called, why is the static method of the parent class called?

  Look at the code first:

public class Person {
    public static void main(String[] args) {
        //编译看左边
        PersonFather person=new Personson();
        person.scrore=100;
        person.eat();
        person.sleep();
        System.out.println(person.scrore+" ,");
    }

}
class PersonFather{
    String name="父类";
    int scrore=1000;
    public static void eat(){
        System.out.println("我是父类的静态吃方法");
    }
    public void sleep(){
        System.out.println("我是父类的睡觉静态方法");
    }
}
class Personson extends PersonFather{
    String name="子类";
    int score=10;
    public static void eat(){
        System.out.println("我是子类的静态吃方法");
    }
    public void sleep(){
        System.out.println("我是子类的睡觉静态方法");
    }

}

Knowledge base:

  1. When the member methods and variables modified by Stastic are loaded, they are loaded along with the class loading. His life cycle is the same as that of the class.

  2. Subclasses will inherit all properties and methods, except private ones. Therefore, when the subclass is loaded, the properties and methods of the parent class are loaded first, and then the subclass is loaded.

When learning polymorphism before: the method is to compile to the left and run to the right. But the subclass inherits the static method of the parent class, using polymorphism will not rewrite or overwrite the method of the parent class. Because the static method of the parent class is loaded following the loading of the parent class, the static method of the parent class is called instead of the static method of the subclass.

operation result:

Guess you like

Origin blog.csdn.net/qq_50692350/article/details/126268591