我正在学习枚举,但不了解此方法的用途.
例:
enum Fruits{
apple, pear, orange
}
class Demo{
f = Fruits.valueOf("apple"); //returns apple... but I had to type it!
// so why wouldn't I save myself some time
// and just write: f = Fruits.apple; !?
}
解决方法:
valueOf方法的重点是为您提供一种获取以字符串形式呈现给程序的Fruits值的方法-例如,当值来自配置文件或用户输入时:
String fruitName = input.next();
Fruits fruit = Fruits.valueOf(fruitName);
上面,水果的名称由最终用户提供.您的程序可以将其作为枚举读取和处理,而不需要在运行时提供哪种水果.