枚举:使用枚举和 class 静态变量的区别
Enum : Difference between using enum and class with static variables
我有一个关于使用 enum
和使用 java class
以及定义 static variables
的小问题。
例如我们可以这样定义枚举:-
public enum RequestCodeEnum {
TRANSACTION(1), REPORTS(2), BUDGET(3), CATEGORY(4), CURRENCY(5);
private int value;
private RequestCodeEnum(int value) {
this.value = value;
}
public int getCode(){
return value;
}
}
同样,我们可以使用带有静态变量的 java class :-
public class ActivityRequestCode {
public static int TRANSACTION_CODE = 1;
public static int REPORTS = 2;
public static int BUDGET = 3;
public static int CATEGORY = 4;
public static int CURRENCY = 5;
}
为了调用两个 classes,我们可以这样做 :-
int i = RequestCodeEnum.CATEGORY.getCode();
int j = ActivityRequestCode.TRANSACTION_CODE;
我想知道它会带来什么不同,或者它们是相互替代的解决方案。 7
谢谢。
不同之处在于常量在 Android 上是首选,因为它们占用的内存更少。
Enums often require more than twice as much memory as static
constants. You should strictly avoid using enums on Android.
见https://developer.android.com/topic/performance/memory.html
我有一个关于使用 enum
和使用 java class
以及定义 static variables
的小问题。
例如我们可以这样定义枚举:-
public enum RequestCodeEnum {
TRANSACTION(1), REPORTS(2), BUDGET(3), CATEGORY(4), CURRENCY(5);
private int value;
private RequestCodeEnum(int value) {
this.value = value;
}
public int getCode(){
return value;
}
}
同样,我们可以使用带有静态变量的 java class :-
public class ActivityRequestCode {
public static int TRANSACTION_CODE = 1;
public static int REPORTS = 2;
public static int BUDGET = 3;
public static int CATEGORY = 4;
public static int CURRENCY = 5;
}
为了调用两个 classes,我们可以这样做 :-
int i = RequestCodeEnum.CATEGORY.getCode();
int j = ActivityRequestCode.TRANSACTION_CODE;
我想知道它会带来什么不同,或者它们是相互替代的解决方案。 7
谢谢。
不同之处在于常量在 Android 上是首选,因为它们占用的内存更少。
Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.
见https://developer.android.com/topic/performance/memory.html