题目:
解法一:
package exercism;import java.util.HashMap;
import java.util.Map;public class ResistorColor {
private Map<String,Integer> colorMap;private String[] colors = {
"Black","Brown","Red","Orange","Yellow","Green","Blue","Violet","Grey","White"};private Integer[] points = {
0,1,2,3,4,5,6,7,8,9};public ResistorColor() {
colorMap = new HashMap<>();for (int i = 0; i < colors.length; i++) {
colorMap.put(colors[i],points[i]);}}public int colorCode(String color) {
return colorMap.get(color);}public String[] getColors() {
return colors;}}
解法二:
class ResistorColor {
String[] colors() {
return new String[]{
"black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white"};int colorCode(String color) {
return java.util.Arrays.asList(colors()).indexOf(color);// 只有List才有indexOf方法}}
}
解法三:
import static java.util.Arrays.stream;class ResistorColor {
private enum Colors {
black, brown, red, orange, yellow, green, blue, violet, grey, white}int colorCode(String color) {
return Colors.valueOf(color).ordinal();}String[] colors() {
return stream(Colors.values()).map(Enum::name).toArray(String[]::new);}
}
Conclusion:
- enum类.valueof().ordinal()方法可以获得field的下标
- “::” 左边表示作用域(类或对象)、右边表示作用域的方法