JAVA不可變類(immutable)機制與String的不可變性

來源:互聯網
上載者:User

標籤:不可變   tps   數組   沒有   .sql   無法   first   www.   iss   

不可變類:是指這個類執行個體一旦建立,就不能不該其成員變數的值

優點:

1.安全執行緒 對象的值無法改變,降低並發錯誤的可能性

2.效率高  當一個對象需要複製時,就只需要複製對象地址,不用複製本生

      不變性,保證了hashcode的唯一性,每次緩衝時不必重新計算hashcode,所以常用string作為key

 

3.便於測試 而且如果程式裡的變數都是immutable 的話 side effect就比較小 程式只要寫好測一遍基本沒有什麼bug

缺點:

每一次改變都需要產生新的對象,容易產生很多垃圾

設計方法:

類添加final修飾符,保證類不被繼承

保證所有成員變數private final

不提供 setter

初始設定變數時,使用deep copy

public final class ImmutableDemo {      private final int[] myArray;      public ImmutableDemo(int[] array) {         // this.myArray = array; // wrong             this.myArray = array.clone();    }  }

getter方法返回對像複製,不返回本身 

String對象

public final class String    implements java.io.Serializable, Comparable<String>, CharSequence{    /** The value is used for character storage. */    private final char value[];    /** The offset is the first index of the storage that is used. */    private final int offset;    /** The count is the number of characters in the String. */    private final int count;    /** Cache the hash code for the string */    private int hash; // Default to 0    ....    public String(char value[]) {         this.value = Arrays.copyOf(value, value.length); // deep copy操作     }    ...     public char[] toCharArray() {     // Cannot use Arrays.copyOf because of class initialization order issues        char result[] = new char[value.length];        System.arraycopy(value, 0, result, 0, value.length);        return result;    }    ...}

  適用於常量池

  安全執行緒

  類載入器要用到字串,不可變類提供安全性,便於正確載入 譬如你想載入java.sql.Connection類,而這個值被改成了myhacked.Connection,那麼會對你的資料庫造成不可知的破壞。

  適用於hashmap

注意:string可以通過反射機制改變值

    //建立字串"Hello World", 並賦給引用s    String s = "Hello World";     System.out.println("s = " + s); //Hello World    //擷取String類中的value欄位    Field valueFieldOfString = String.class.getDeclaredField("value");    //改變value屬性的存取權限    valueFieldOfString.setAccessible(true);    //擷取s對象上的value屬性的值    char[] value = (char[]) valueFieldOfString.get(s);    //改變value所引用的數組中的第5個字元    value[5] = ‘_‘;    System.out.println("s = " + s);  //Hello_World

  結果:

s = Hello Worlds = Hello_World

  參考:

  https://www.cnblogs.com/jaylon/p/5721571.html

  https://www.cnblogs.com/zhiheng/p/6653969.html

 

JAVA不可變類(immutable)機制與String的不可變性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.