Statements Updated for Enumerations

Two statements have been changed to make them work better with enumerations: the switch statement, and the for statement.

Using a for statement with enums

Language designers want to make it easy to express the concept “Iterate through all the values in this enumeration type”. There was much discussion about how to modify the “for” loop statement. It was done in a clever way—by adding support for iterating through all the values in any array.

Here is the new “get all elements of an array” syntax added to the “for” statement.

// for each Dog object in the dogsArray[] print out the dog's name
for (Dog dog : dogsArray ){
    dog.printName();
}

This style of “for” statement has become known as the “foreach” statement (which is really goofy, because there is no each or foreach keyword). The colon is read as “in”, so the whole thing is read as “for each dog in dogsArray”. The loop variable dog iterates through all the elements in the array starting at zero.

Using the new foreach feature, we can now write a very brief program that echoes the arguments from the command line. The command line arguments (starting after the main class name) are passed to main() in the String array parameter. We print it out like this:

public class echo {
    public static void main( String[] args) {
        for (String i : args )
            System. out. println("arg = " + i);
    }
}

Compiling and running the program with a few arguments gives this:

javac -source 1.5 -target 1.5 echo. java

java echo test data here
arg = test
arg = data
arg = here

Note: The final decision on whether to have a “-source 1.5” compiler option and what it should look like had not been made when this book went to press. See the website www.afu.com/jj6 for the latest information. You can set it up in a batch file so you don't have to keep typing it.

The same for loop syntax can be used for enums if you can somehow get the enum constants into an array. And that's exactly how it was done. Every enum type that you define automatically brings into existence a class method called values().

The values() method for enums

The values() method is created on your behalf in every enum you define. It has a return value of an array, with successive elements containing the enum values. That can be used in for loops as the example shows:

for (Bread b : Bread.values() ) {

    // b iterates through all the Bread enum constants
    System.out.println("bread type = " + b);
}

In addition to the enum constants that you write, the enum type can contain other fields. The values() method is one of them. Bread.values() is a call to a class method belonging to the Bread enum. The method is invoked on the enum class type Bread, not on an instance, so we can conclude it must be a class method.

You can even iterate through a subrange of an enum type. The class java.util. EnumSet has a method called range() that takes various arguments, and returns a value suitable for use in the expanded for statement.

You would use it like this:

public class Example {
   enum Month {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }
   public static void main(String[] args) {

      for (Month m : java.util.EnumSet.range(Month.Jun, Month.Aug) )
                 System.out.println("summer includes: " + m );
   }
}

When compiled and run, that prints:

summer includes: Jun
summer includes: Jul
summer includes: Aug

The method range() belonging to class EnumSet returns, not an array (as you might guess), but an object of type EnumSet. The “for” statement has been modified to accept an array or an EnumSet in this kind of loop (it can accept a Collection class too).

Modifying the “for” loopto allow a special type here was done as a concession to performance improvement. An EnumSet is a collection class that can hold multiple enum constants from any one enum type. They don't have to be a consecutive range of enum constants. If there are 64 or fewer enum constants in the set, it will store the set as a long word of bits, and not as an array of references. This makes it very fast to tell if an enum constant is in or out of the set, and very fast to iterate through a range of enum constants.

Using a switch statement with enums

You can now use an enum type in a “switch” statement (Java's name for the case statement used in other languages). Formerly, the switch expression had to be an int type. Here's an example that uses an enum in a switch statement.

Bread myLoaf = Bread.rye;
int price = 0;

switch (myLoaf) {
    case wholewheat: price = 190;
                     break;

    case     french: price = 200;
                     break;

     case ninegrain: price = 250;
                     break;

           case rye: price = 275;
                     break;
}

System.out.println( myLoaf + " costs " + price);

The “break” statement causes the flow of control to transfer to the end of the switch. Without that, program execution drops through into the next case clause. Running the program gives the output:

rye costs 275

The enum value in the case switch label must be an unqualified name. That is, you must write “rye” and not “Bread. rye”. That (unfortunately) contrasts with an assignment to an enum variable. In an assignment:

myLoaf = Bread.rye;

you must use the qualified name Bread.rye, unless you import the type name.

Dropping the need to qualify names—import

We mentioned above that you must use the qualified name, such as Bread.rye, unless you import the type name. This section explains how to do that, using a wordy example from the digital clock in Chapter 2. That program had a statement saying:

this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

The statement is setting how the window should behave when the user clicks on the close icon on the title bar. There's a choice of four alternatives, ranging from “ignore it” to “terminate the program”. The alternatives are represented by integer constants in class WindowConstants, which is part of package javax.swing. Here is the source code from the Java run-time library, defining those constants:

public static final int DO_NOTHING_ON_CLOSE = 0;
public static final int HIDE_ON_CLOSE = 1;
public static final int DISPOSE_ON_CLOSE = 2;
public static final int EXIT_ON_CLOSE = 3;

Those could be better expressed as an enum type, but this code was written long before Java supported enum types. It would be nice if the programmer using those constants didn't have to mention the lengthy names of the package and subpackage they come from.

That's exactly what the “import” statement gives you. The import statement has been part of Java from the beginning. It lets a programmer write this:

import java.swingx.*;   // import all classes in package java.swingx

or

import java.swingx.WindowConstants;  // import this class

The “import” statements (if any) appear at the top of the source file, right after the optional line that says what package this file belongs to. The imports apply to all the rest of the file. The import statement brings into your namespace one or more classes from a package. The import with the asterisk is meant to be like a wildcard in a file name. It means “import all classes from the package”. So “import javax.swing.*;” means you can drop the “javax.swing” qualifier from class names from the javax.swing package.

The second version, importing a single class, means that you do not have to qualify that one class with its package name at each point you mention it.

Import is purely a compile time convenience feature. It does not make a class visible that was not visible before. It does not make any change to the amount of code that is linked into your executable. It just lets you refer to a class without qualifying it with the full name of the package it is in.

Either of these imports would allow us to cut down our “close window” statement to:

this.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );

Using “import static”

image

We are still required to mention the class name, and this is where the new feature of static import comes in. JDK 1.5 adds the ability to import the static members from a class, or the enum values from an enum type. It is analogous to the ordinary import statement, and it looks like this:

import static qualified_class_name.*;

or

import static qualified_enum_name.*;

So you can now write

import static javax.swing.WindowConstants.*;
   /* more code */
  this.setDefaultCloseOperation(EXIT_ON_CLOSE);

The this can be implicit, so what started out as

this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

can now be written as

import static javax.swing.WindowConstants.*;
  //  lots more code here
setDefaultCloseOperation(EXIT_ON_CLOSE);

Similarly, using enums and static import we can write:

import static mypackage.Bread.* ;
      // more code here

       Bread myLoaf = rye;

You can import just one enum value or static member, by appending its name instead of using the “*” to get all of them. Don't forget that to compile anything with the new JDK 1.5 features, you need to use these options on the command line:

javac -source 1.5 -target 1.5 sourcefiles.java

You can use import static on the System class to shorten the name of the utility that does console I/O. Before import static, I used to create an alias like this:

java.io.PrintStream o = System.out;
o.println("hello Bob");

Now you can “import static” instead.

import static java.lang.System.out; /* more code omitted */
out.println("hello Bob");

The compiler is quite capable of figuring out whether you are importing a static member or a classname within a package, so the "import static" keywords could have been left as just the old "import" keyword. It was considered better to remind the programmer that only static members can be imported, not instance members.

What if you import static WarmColors and Fruits? You can do this (they will need to be in a named package, not the default anonymous package used in the examples). But any place where you use one of the named constants whose name is duplicated, you will have to provide the full qualified name:

Fruit f = Fruit.peach;
Fruit f2 =      apple;  // unique name, so no qualifier needed.

At this point we've covered everything relating to enums that you'll see 99% of the time. There is some more material, but you can safely skip the rest of the chapter, and return when you have some specific enum construct to decode.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.35.193