effective java——31用实例域代替序数

时间:2022-07-24 14:24:27

1,永远不要根据枚举的序数导出与它关联的值,而是要将他保存在一个实例域中。(ordinal())

public enum Ensemble {
SOLO, DUET, TRIO, QUARTET, QUINTET, SEXTET, SEPTET, OCTET, NONET, DECTET;

public int numberOfMusicians() {
return ordinal()+1;
}
}
无法添加

所以可以采用以下方式:

public enum Ensemble {
SOLO(1), DUET(2), TRIO(3), QUARTET(4), QUINTET(5), SEXTET(6), SEPTET(7), OCTET(8),
DOUBLE_QUARTET(8), NONET(9), DECTET(10), TRIPLE_QUARTET(12);

private final int numberOfMusicians;

Ensemble(int size) {
this.numberOfMusicians = size;
}

public int numberOfMusicians() {
return numberOfMusicians;
}
}