四、泛型(完全不懂)
五、枚举和注解
1、用enum代替int常量
- 这个经常用,一般好像都是这么用的了,这里注意有个values()方法挺有意思
public enum Planet {
MERCURY(3.302e+23, 2.439e6), VENUS(4.869e+24, 6.052e6), EARTH(5.975e+24,
6.378e6);
private final double mass;
private final double radius;
private final double surfaceGravity;
private static final double G = 6.67300E-11;
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
surfaceGravity = G * mass / (radius * radius);
}
public double surfaceGravity() {
return surfaceGravity;
}
public double surfaceWeight(double mass) {
return mass * surfaceGravity;
}
}
public static void main(String[] args) {
double earthWeight = 1.0d;
double mass = earthWeight / Planet.EARTH.surfaceGravity();
for (Planet p : Planet.values())
System.out.printf("Weight on %s is %f%n", p, p.surfaceWeight(mass));
}
2、用实例域代替序数
- 枚举是有顺序的,但是维护起来是噩梦
- 所以现在都是SOLO(1), SUET(2);这样了
3、用EnumSet代替位域
public class Text {
public enum Style {
BOLD, ITALIC, UNDERLINE, STRIKETHROUGH
}
public void applyStyles(Set