Java 1.5 Tiger A Developers Notebook [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Java 1.5 Tiger A Developers Notebook [Electronic resources] - نسخه متنی

David Flanagan, Brett McLaughlin

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید








3.3 Iterating Over Enums


Ever been given a class with
lousy documentation, no source code, and
little instruction on its use? Welcome to the loosely knit organization of
real-world programmers. In many cases, you can resort to reflection to
figure out what a class has to offer in lieu of source code, and of course
JavaDoc is always helpful. In the case of enumerated types, though,
there's a nice built-in
feature: the values( ) method. This method provides
access to all of the types within an enum.


3.3.1 How do I do that?


Invoking the values( ) method on an enum returns an array of all the
values in the type:


public void listGradeValues(PrintStream out) throws IOException {
Grade[] gradeValues = Grade.values( );
for (Grade g : Grade.values( )) {
out.println("Allowed value: '" + g + "'");
}
}

This is a nice way to get a quick dump of all the allowed values for a
particular enum:


run-ch03:
[echo] Running Chapter 3 examples from Java 1.5: A Developer's Notebook
[echo] Running GradeTester...
[java] Allowed value: 'A'
[java] Allowed value: 'B'
[java] Allowed value: 'C'
[java] Allowed value: 'D'
[java] Allowed value: 'F'
[java] Allowed value: 'INCOMPLETE'

NOTE

Run this sample
with the Ant
target "run-ch03".


3.3.2 What just happened?


First, note that type-safety is employed. values( ) doesn't return an
array of String valuesinstead it returns an array of Grade instances. In
the out.println( ) statement, each Grade has its toString( ) method executed, which in turn does provide a String name for the value. At no
point are you working with integer constants or even String valuesthe
Grade object hides all these implementation details from you, and allows
strict compile-time checking.


3.3.3 What about...


...using a for/in loop? Well, you're ahead of mefor/in isn't covered
until Chapter 7. Still, for those of you who are curious, you can indeed
perform the same iteration with Tiger's new for/in capabilities:


// for/in loop
for (Grade g : grade.values( )) {
out.println("Allowed value: '" + g + "'");
}


/ 131