「Java」「abstract」 Chapter4 Question2
Given:
Answer:
參考網址:
enum Car { Toyota, Honda, Suzuki, Nissan; } public class Brand { public static void main(String[] args) { for(Car d: Car.values()) {//正確,印出 ToyotaHondaSuzukiNissan System.out.print(d); } for(Car d1: Car.asList()) { //The method asList() is undefined for the type Car System.out.print(d1); } for(Car d2: Car.iterator()) {//The method iterator() is undefined for the type Car System.out.print(d2); } for(Car d3: Car.asArray()) {//The method asArray() is undefined for the type Car System.out.print(d3); } } }
Answer:
參考網址:
You can't see this method in javadoc because it's added by the compiler.
Documented in three places :
Documented in three places :
The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.
Enum.valueOf
class
(The special implicitvalues
method is mentioned in description ofvalueOf
method)
All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.The
values
function simply list all values of the enumeration.
翻譯:
這個問題你是無法在Java Doc 中找到,因為這是在編譯過程中添加的。
記錄在三個文件中:
在建立列舉的編譯過程中會自動添加一些特殊的方法。例如:它們有一個靜態方法,該方法宣告時能呼叫陣列中的所有內容。 此方法通常與for-each結合,取得列舉的內容。
列舉的 valueOf 方法
所有列舉型別的常量數值,可通過隱含式 public static T[] values()的方法型別呼叫取得。
枚舉型別,第8與9節,Java規範
values功能只列出列舉的所有值。
留言
張貼留言