Java面試八股文01-基礎部分

赵文梦發表於2024-03-14

Java檔案執行流程

  • 編譯:將.java檔案編譯為虛擬機器可以識別的.class位元組碼檔案
  • 解釋:虛擬機器執行java位元組碼檔案,將其轉化為機器可以執行的機器碼
  • 執行:機器執行機器碼

物件導向的三大特性

  • 封裝
  • 繼承
  • 多型

深複製和淺複製

  • 淺複製程式碼舉例
public class Person implements Cloneable {
    private Address address;

    public Person(Address address){
        this.address = address;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class Address implements Cloneable{
    private String name;

    public Address(String name){
        this.name = name;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public static void main(String[] args) throws CloneNotSupportedException {
        Person person1 = new Person(new Address("北京"));
        Person person2 = (Person)person1.clone();
        System.out.println(person1 == person2); //false
        System.out.println(person1.getAddress() == person2.getAddress()); //true
    }

淺複製之後物件重新複製了一份,但是在物件裡面的引用並沒有重新複製

  • 深複製程式碼舉例
public class Address implements Cloneable{
    private String name;

    public Address(String name){
        this.name = name;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

public class Person implements Cloneable {
    private Address address;

    public Person(Address address){
        this.address = address;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        try {
            Person person = (Person) super.clone();
            person.setAddress((Address) person.getAddress().clone());
            return person;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }
}
public static void main(String[] args) throws CloneNotSupportedException {
        Person person1 = new Person(new Address("北京"));
        Person person2 = (Person)person1.clone();
        System.out.println(person1 == person2); //false
        System.out.println(person1.getAddress() == person2.getAddress()); //false
    }

深複製不僅僅複製了物件,還複製了物件裡面的引用,此外深複製還可以使用序列化方式進行複製

  • 另外還有一種引用複製,就是直接引用使用的物件,即直接指向該物件堆中的地址,不進行複製

hashCode()和equals()

每個物件都有一個hashCode,相同物件的hashCode肯定是一樣的,所以可以使用hashCode來判斷物件是否相等來提高判斷效率,但是也有小機率不同的物件的hashCode也是相同的,所以要使用equals來保證判斷物件完整與否的準確性,在使用過程中,首先使用hashCode,如果hashCode不相等,那麼他們絕對不是相同的,如果他們相等,則會再使用equals來判斷這兩個物件是否相等

String重點問題

相關文章