使用列舉為甚佔用更多的空間
阿新 • • 發佈:2019-02-10
列舉是強型別資料,具有更高的安全性,並且它將執行期的引數檢查放到了編譯期,保證了程式碼編寫的準確性,提高了程式碼的可讀性,但是,列舉也並非完美的的,它會佔用更多的空間
測試程式碼:
public enum Season { Spring(1,"春","cyan","warmth"){ public void doSomething(){}; },Summer(2,"夏","green","hot"){ public void doSomething(){}; }, Autumn(3,"秋","yellow","cool"){ public void doSomething(){}; },Winter(4,"冬","white","cold"){ public void doSomething(){}; }; private int code; private String name; private String color; private String feel; Season(int code, String name, String color, String feel) { this.code = code; this.name = name; this.color = color; this.feel = feel; } public int getCode() { return code; } public String getName() { return name; } public String getColor() { return color; } public String getFeel() { return feel; } }
接下來使用javac命令進行編譯:
如果編譯時提示:編碼GBK的不可對映字元,可以在命令後面加入-encoding UTF-8 如:javac -encoding UTF-8 Season.java
可以看出,編譯後產生了五個檔案,這五個檔案是什麼呢?我們可以使用javap反編譯指令來檢視其中的內容
Season$1.class
由於Season$2~$4的內容一樣,就不一一列出了
下面是Season.class的內容
可以看出列舉型別使用了public static final 關鍵字修飾
但是這僅僅是體現在檔案數量上嗎
在開發時,我們還常常使用零另一種方式定義一些公共的,不變的量,那就是靜態常量,下面使用靜態變數來進行測試
測試程式碼
public class Season {
public static final int SPRING=1;
public static final int SUMMER=2;
public static final int ATUMN=3;
public static final int WINTER=4;
}
使用javac編譯後值產生了一個檔案
可以看出,兩個檔案大小差了十多倍