Java枚举
1. 枚举常量
```
public enum Color {
Red, Green, Blue;
}
```
用这个枚举
因为枚举.values返回的是个数组,所以可以用索引操作。
```
public static void main(String[] args) {
System.out.println(Color.Red);
System.out.println(Color.values()[0]);
}
```
2. 向枚举中添加方法
我们先给枚举搞两个属性,并添加构造方法getter,setter方法。
```
public enum Color{
Red("红色",1),Blue("蓝色",2),Green("绿色",3);
private String name;
private Integer index;
Color(String name, Integer index) {
this.name = name;
this.index = index;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
}
```
添加方法,在main中执行。
```
package com.hxut.controller;
public class _Enum {
public enum Color{
Red("红色",1),Blue("蓝色",2),Green("绿色",3);
private String name;
private Integer index;
Color(String name, Integer index) {
this.name = name;
this.index = index;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public static String getName(Integer index){
for(Color c:Color.values()){
if(c.getIndex()==index){
return c.getName();
}
}
return null;
}
}
public static void main(String[] args) {
String name = Color.getName(1);
System.out.println(name);
}
}
```
3. 枚举实现方法
```
package com.hxut.controller;
public class _Enum {
public interface behaviour{
String info();
void print();
}
public enum Color implements behaviour{
Red("红色",1),Blue("蓝色",2),Green("绿色",3);
private String name;
private Integer index;
Color(String name, Integer index) {
this.name = name;
this.index = index;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public static String getName(Integer index){
for(Color c:Color.values()){
if(c.getIndex()==index){
return c.getName();
}
}
return null;
}
@Override
public String info() {
return this.name;
}
@Override
public void print() {
System.out.println(this.name+"->"+this.index);
}
}
public static void main(String[] args) {
String name = Color.getName(1);
System.out.println(name);
Color color = Color.valueOf(Color.class, "Red");
color.info();
color.print();
}
}
注意实现这些方法,调用好像只能通过valueOf返回的是一个数组,通过这个对象调用接口的方法。
```