Java/Language Basics/Enum

Материал из Java эксперт
Перейти к: навигация, поиск

An enumeration of apple varieties.

   <source lang="java">

enum Apple {

 A, B, C, D, E 

}

public class EnumDemo {

 public static void main(String args[])  
 { 
   Apple ap; 

   ap = Apple.C; 

   // Output an enum value. 
   System.out.println("Value of ap: " + ap); 
   System.out.println(); 

   ap = Apple.B; 

   // Compare two enum values. 
   if(ap == Apple.B)  
     System.out.println("ap conatins GoldenDel.\n"); 

   // Use an enum to control a switch statement. 
   switch(ap) { 
     case A: 
       System.out.println("A is red."); 
       break; 
     case B: 
       System.out.println("B is yellow."); 
       break; 
     case C:  
       System.out.println("C is red."); 
       break; 
     case D: 
       System.out.println("D is red."); 
       break; 
     case E: 
       System.out.println("E is red."); 
       break; 
   } 
 } 

}


      </source>
   
  
 
  



Enum and Generic

   <source lang="java">

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.InputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /**

* MediaInvoicer - Simple applicatin of Media, MediaFactory &c.
* 
* @author ian
* @version $Id: MediaInvoicer.java,v 1.2 2004/03/08 03:30:59 ian Exp $
*/

public class MediaInvoicer {

 public static void main(String[] args) throws IOException {
   MediaInvoicer mi = new MediaInvoicer(System.in);
   Invoice i = mi.getInvoice();
   i.print(System.out);
 }
 BufferedReader myFile;
 public MediaInvoicer(InputStream is) {
   myFile = new BufferedReader(new InputStreamReader(is));
 }
 public Invoice getInvoice() throws IOException {
   String line;
   List < Item > items = new ArrayList < Item > ();
   while ((line = myFile.readLine()) != null) {
     if (line.startsWith("#")) {
       continue;
     }
     StringTokenizer st = new StringTokenizer(line);
     st.nextToken();
     Media m = MediaFactory.getMedia(st.nextToken());
     int stock = Integer.parseInt(st.nextToken());
     int qty = Integer.parseInt(st.nextToken());
     Item tmp = new Item(m, stock, qty);
     items.add(tmp);
   }
   return new Invoice(1, 3,
     (Item[]) items.toArray(new Item[items.size()]));
 }
 /** Inner class for line order item */
 class Item {
   Media product;
   int stockNumber;
   int quantity;
   /**
    * @param product
    * @param stockNumber
    * @param quantity
    */
   public Item(Media product, int stockNumber, int quantity) {
     super();
     this.product = product;
     this.stockNumber = stockNumber;
     this.quantity = quantity;
   }
   public String toString() {
     return "Item[" + product + " " + stockNumber + "]";
   }
 }
 /** Inner class for one invoice */
 class Invoice {
   int orderNumber;
   int custNumber;
   Item[] items;
   public Invoice(int orderNumber, int custNumber, Item[] items) {
     super();
     this.orderNumber = orderNumber;
     this.custNumber = custNumber;
     this.items = items;
   }
   public void print(PrintStream ps) {
     ps.println("*** Invoice ***");
     ps.println("Customer: " + custNumber + ")");
     ps.println("Our order number: " + orderNumber);
     for (int i = 0; i < items.length; i++) {
       Item it = items[i];
       ps.println(it);
     }
   }
 }

}

enum Media {

 book, music_cd, music_vinyl, movie_vhs, movie_dvd;

}


      </source>
   
  
 
  



Enum with switch statement

   <source lang="java">

import java.util.*; enum OperatingSystems {

   windows, unix, linux, macintosh

} public class EnumExample1 {

   public static void main(String args[])
   {
       OperatingSystems os;
       os = OperatingSystems.windows;
       switch(os) {
           case windows:
               System.out.println("You chose Windows!");
               break;
           case unix:
               System.out.println("You chose Unix!");
               break;
           case linux:
               System.out.println("You chose Linux!");
               break;
           case macintosh:
               System.out.println("You chose Macintosh!");
               break;
           default:
               System.out.println("I don"t know your OS.");
               break;
       }
   }

}


      </source>
   
  
 
  



How to use enum

   <source lang="java">

enum ProgramFlags {

   showErrors(0x01),
   includeFileOutput(0x02),
   useAlternateProcessor(0x04);
   private int bit;
   ProgramFlags(int bitNumber)
   {
       bit = bitNumber;
   }
   public int getBitNumber()
   {
       return(bit);
   }

} public class EnumBitmapExample {

   public static void main(String args[])
   {
       ProgramFlags flag = ProgramFlags.showErrors;
       System.out.println("Flag selected is: " +
                               flag.ordinal() +
                          " which is " +
                               flag.name());
   }

}

      </source>
   
  
 
  



Java enum: Creating an Enum

   <source lang="java">

/* License for Java 1.5 "Tiger": A Developer"s Notebook

    (O"Reilly) example package

Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) by Brett McLaughlin and David Flanagan. ISBN: 0-596-00738-8 You can use the examples and the source code any way you want, but please include a reference to where it comes from if you use it in your own products or services. Also note that this software is provided by the author "as is", with no expressed or implied warranties. In no event shall the author be liable for any direct or indirect damages arising in any way out of the use of this software.

  • /

import java.io.IOException; import java.io.PrintStream; enum Grade { A, B, C, D, F, INCOMPLETE }; class Student {

 private String firstName;
 private String lastName;
 private Grade grade;
 public Student(String firstName, String lastName) {
   this.firstName = firstName;
   this.lastName = lastName;
 }
 public void setFirstName(String firstName) {
   this.firstName = firstName;
 }
 public String getFirstName() {
   return firstName;
 }
 public void setLastName(String lastName) {
   this.lastName = lastName;
 }
 public String getLastName() {
   return lastName;
 }
 public String getFullName() {
   return new StringBuffer(firstName)
          .append(" ")
          .append(lastName)
          .toString();
 }
 public void assignGrade(Grade grade) {
   this.grade = grade;
 }
 public Grade getGrade() {
   return grade;
 }

} public class GradeTester {

 private Student student1, student2, student3;
 public GradeTester() { 
   student1 = new Student("Brett", "McLaughlin");
   student2 = new Student("Ben", "Rochester");
   student3 = new Student("Dennis", "Erwin");
 }
 public void testGradeAssignment(PrintStream out) throws IOException {
   student1.assignGrade(Grade.B);
   student2.assignGrade(Grade.INCOMPLETE);
   student3.assignGrade(Grade.A);
 }
 public void listGradeValues(PrintStream out) throws IOException {
   Grade[] gradeValues = Grade.values();
   // for loop
   for (int i=0; i<gradeValues.length; i++) {
     out.println("Allowed value: "" + gradeValues[i] + """);
   }
   // for/in loop
   for (Grade g : gradeValues ) {
     out.println("Allowed value: "" + g + """);
   }
 }
 public void testSwitchStatement(PrintStream out) throws IOException {
   StringBuffer outputText = new StringBuffer(student1.getFullName());
   switch (student1.getGrade()) {
     case A: 
       outputText.append(" excelled with a grade of A");
       break;   
     case B: // fall through to C
     case C: 
       outputText.append(" passed with a grade of ")
                 .append(student1.getGrade().toString());
       break;
     case D: // fall through to F
     case F:
       outputText.append(" failed with a grade of ")
                 .append(student1.getGrade().toString());
       break;
     case INCOMPLETE:
       outputText.append(" did not complete the class.");
       break;
     default:
       outputText.append(" has a grade of ")
                 .append(student1.getGrade().toString());
       break;
   }
   out.println(outputText.toString());
 }
 public static void main(String[] args) {
   try {
     GradeTester tester = new GradeTester();
 
     tester.testGradeAssignment(System.out);
     tester.listGradeValues(System.out);
     tester.testSwitchStatement(System.out);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }

}

      </source>
   
  
 
  



Java enum: Demonstrate ordinal(), compareTo(), and equals().

   <source lang="java">

/* Java 2, v5.0 (Tiger) New Features by Herbert Schildt ISBN: 0072258543 Publisher: McGraw-Hill/Osborne, 2004

  • /

//

// An enumeration of apple varieties. enum Apple {

 Jonathan, GoldenDel, RedDel, Winsap, Cortland 

}

public class EnumDemo4 {

 public static void main(String args[])  
 { 
   Apple ap, ap2, ap3; 

   // Obtain all ordinal values using ordinal(). 
   System.out.println("Here are all apple constants" + 
                      " and their ordinal values: "); 
   for(Apple a : Apple.values()) 
     System.out.println(a + " " + a.ordinal()); 

   ap =  Apple.RedDel; 
   ap2 = Apple.GoldenDel; 
   ap3 = Apple.RedDel; 

   System.out.println(); 

   // Demonstrate compareTo() and equals() 
   if(ap.rupareTo(ap2) < 0) 
     System.out.println(ap + " comes before " + ap2); 

   if(ap.rupareTo(ap2) > 0) 
     System.out.println(ap2 + " comes before " + ap); 

   if(ap.rupareTo(ap3) == 0) 
     System.out.println(ap + " equals " + ap3); 
  
   System.out.println(); 

   if(ap.equals(ap2)) 
     System.out.println("Error!"); 

   if(ap.equals(ap3)) 
     System.out.println(ap + " equals " + ap3); 

   if(ap == ap3) 
     System.out.println(ap + " == " + ap3); 

 } 

}

      </source>
   
  
 
  



Java enum: Enum inside class

   <source lang="java">

/* License for Java 1.5 "Tiger": A Developer"s Notebook

    (O"Reilly) example package

Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) by Brett McLaughlin and David Flanagan. ISBN: 0-596-00738-8 You can use the examples and the source code any way you want, but please include a reference to where it comes from if you use it in your own products or services. Also note that this software is provided by the author "as is", with no expressed or implied warranties. In no event shall the author be liable for any direct or indirect damages arising in any way out of the use of this software.

  • /

public class Downloader {

 public enum DownloadStatus { INITIALIZING, IN_PROGRESS, COMPLETE };
 // Class body

}

      </source>
   
  
 
  



Java enum: EnumMap and Ant status

   <source lang="java">

/* License for Java 1.5 "Tiger": A Developer"s Notebook

    (O"Reilly) example package

Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) by Brett McLaughlin and David Flanagan. ISBN: 0-596-00738-8 You can use the examples and the source code any way you want, but please include a reference to where it comes from if you use it in your own products or services. Also note that this software is provided by the author "as is", with no expressed or implied warranties. In no event shall the author be liable for any direct or indirect damages arising in any way out of the use of this software.

  • /

import java.io.IOException; import java.io.PrintStream; import java.util.EnumMap; enum AntStatus {

 INITIALIZING,
 COMPILING,
 COPYING,
 JARRING,
 ZIPPING,
 DONE,
 ERROR

} public class AntStatusTester {

 public AntStatusTester() { }
 public void testEnumMap(PrintStream out) throws IOException {
   // Create a map with the key and a String message
   EnumMap<AntStatus, String> antMessages =
     new EnumMap<AntStatus, String>(AntStatus.class);
   // Initialize the map
   antMessages.put(AntStatus.INITIALIZING, "Initializing Ant...");
   antMessages.put(AntStatus.ruPILING,    "Compiling Java classes...");
   antMessages.put(AntStatus.COPYING,      "Copying files...");
   antMessages.put(AntStatus.JARRING,      "JARring up files...");
   antMessages.put(AntStatus.ZIPPING,      "ZIPping up files...");
   antMessages.put(AntStatus.DONE,         "Build complete.");
   antMessages.put(AntStatus.ERROR,        "Error occurred.");
   // Iterate and print messages
   for (AntStatus status : AntStatus.values() ) {
     out.println("For status " + status + ", message is: " +
                 antMessages.get(status));
   }
 }
 public static void main(String[] args) {
   try {
     AntStatusTester tester = new AntStatusTester();
     tester.testEnumMap(System.out);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }

}


      </source>
   
  
 
  



Media enumeration constants

   <source lang="java">

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

enum Media {

 book, music_cd, music_vinyl, movie_vhs, movie_dvd;

} /*

* MediaFactory - give out Media enumeration constants
* @version $Id: MediaFactory.java,v 1.2 2004/03/20 20:50:09 ian Exp $
*/

public class MediaFactory {

 public static void main(String[] args) {
   
   System.out.println(MediaFactory.getMedia("Book"));
 }
 public static Media getMedia(String s) {
   return Enum.valueOf(Media.class, s.toLowerCase());
 }
 public static Media getMedia(int n){
   return Media.values()[n];
 }

}


      </source>
   
  
 
  



Switching on Enum and Adding Methods to an Enum

   <source lang="java">

/* License for Java 1.5 "Tiger": A Developer"s Notebook

    (O"Reilly) example package

Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) by Brett McLaughlin and David Flanagan. ISBN: 0-596-00738-8 You can use the examples and the source code any way you want, but please include a reference to where it comes from if you use it in your own products or services. Also note that this software is provided by the author "as is", with no expressed or implied warranties. In no event shall the author be liable for any direct or indirect damages arising in any way out of the use of this software.

  • /

//Implementing Interfaces with Enums enum GuitarFeatures implements Features {

 ROSEWOOD(0),        // back/sides
 MAHOGANY(0),        // back/sides
 ZIRICOTE(300),      // back/sides
 SPRUCE(0),          // top
 CEDAR(0),           // top
 AB_ROSETTE(75),     // abalone rosette
 AB_TOP_BORDER(400), // abalone top border
 IL_DIAMONDS(150),   // diamond/square inlay
 IL_DOTS(0);         // dots inlays
 /** The upcharge for the feature */
 private float upcharge;
 GuitarFeatures(float upcharge) {
   this.upcharge = upcharge;
 }
 public float getUpcharge() {
   return upcharge;
 }
 public String getDescription() {
   switch(this) {
     case ROSEWOOD:      return "Rosewood back and sides";
     case MAHOGANY:      return "Mahogany back and sides";
     case ZIRICOTE:      return "Ziricote back and sides";
     case SPRUCE:        return "Sitka Spruce top";
     case CEDAR:         return "Wester Red Cedar top";
     case AB_ROSETTE:    return "Abalone rosette";
     case AB_TOP_BORDER: return "Abalone top border";
     case IL_DIAMONDS:   
       return "Diamonds and squares fretboard inlay";
     case IL_DOTS:
       return "Small dots fretboard inlay";
     default: return "Unknown feature";
   }
 }

} interface Features {

 /** Get the upcharge for this feature */
 public float getUpcharge();
 /** Get the description for this feature */
 public String getDescription();

}

      </source>
   
  
 
  



Use an enum constructor.

   <source lang="java">

enum Apple {

 A(10), B(9), C, D(15), E(8); 

 private int price; // price of each apple 

 // Constructor 
 Apple(int p) { price = p; } 

 // Overloaded constructor 
 Apple() { price = -1; } 

 int getPrice() { return price; } 

}


      </source>
   
  
 
  



Use an enum constructor, instance variable, and method.

   <source lang="java">

enum Apple {

 A(10), B(9), C(12), D(15), E(8);
 private int price; // price of each apple 
 // Constructor 
 Apple(int p) {
   price = p;
 }
 int getPrice() {
   return price;
 }

} public class EnumDemo3 {

 public static void main(String args[]) {
   Apple ap;
   // Display price of Winsap.
   System.out.println(Apple.A.getPrice());
   // Display all apples and prices.
   System.out.println("All apple prices:");
   for (Apple a : Apple.values())
     System.out.println(a + " costs " + a.getPrice() + " cents.");
 }

}

      </source>
   
  
 
  



Use the built-in enumeration methods.

   <source lang="java">

enum Apple {

 A, B, C, D, E 

}

public class EnumDemo2 {

 public static void main(String args[])  
 { 
   Apple ap; 

   System.out.println("Here are all Apple constants"); 

   // use values() 
   Apple allapples[] = Apple.values(); 
   for(Apple a : allapples) 
     System.out.println(a); 

   System.out.println(); 
   
   // use valueOf() 
   ap = Apple.valueOf("A"); 
   System.out.println("ap contains " + ap); 

 } 

}

      </source>