Java Enumerator (repeating device)

Source: Internet
Author: User
Tags first string

In any collection class, you must place the object in one of the methods, and then take the object from another method. After all, accommodating a wide variety of objects is the primary task of the collection. In vectors, addelement () is the method we insert into the object, and ElementAt () is the only way to extract the object. Vector is very flexible, we can choose anything at any time, and can use different indexes to select multiple elements.
If you look at this problem from a higher angle, you will find a flaw in it: you need to know the exact type of the collection beforehand, otherwise you cannot use it. At first glance, this doesn't seem to matter. But what if you start with a vector and then decide in your program (the reason for execution efficiency) to change into a list (part of the Java1.2 collection library)? The
can be used to achieve this with the concept of "iterator" ("Iterative Device"). It can be an object that iterates through a series of objects and selects each object in that sequence without letting the client programmer know or focus on the underlying structure of that sequence. In addition, we usually think of the iteration as a "lightweight" object; that is, it takes a very small price to create it. But it is for this reason that we often find that there are some seemingly strange limitations to the repetitive device. For example, some iterations can only move in one direction. The
Java enumeration (enumerations, annotation ②) is an example of a repeating device with these limitations. In addition to the following, you can no longer use it to do anything else:
(1) a method called elements () requires a collection to provide us with a enumeration. When we first call its nextelement (), this enumeration returns the first element in the sequence. The
(2) Gets the next object with Nextelement (). The
(3) checks to see if there are more objects in the sequence with hasmoreelements ().

②: The word "iteration" is often present in C + + and other parts of OOP, so it is difficult to determine what Java developers use such a strange name. The Java 1.2 collection library fixes this and many other issues.

can only do these things with enumeration, no more. It is a simple implementation of the repetitive device, but the function is still very powerful. To understand its workings, let's review the Catsanddogs.java procedure mentioned earlier in this chapter. In the original version, the ElementAt () method was used to select each element, but in the following revisions, you can see an enumeration used:
 

//: Catsanddogs2.java//Simple collection with enumeration import java.util.*;
  Class Cat2 {private int catnumber;
  CAT2 (int i) {catnumber = i;
  } void Print () {System.out.println ("Cat number" +catnumber);
  } class Dog2 {private int dognumber;
  DOG2 (int i) {dognumber = i;
  } void Print () {System.out.println ("Dog number" +dognumber);
    } public class CatsAndDogs2 {public static void main (string[] args) {Vector cats = new vector ();
    for (int i = 0; i < 7; i++) cats.addelement (new Cat2 (i));
    Not a problem to add a dog to Cats:cats.addElement (new Dog2 (7));
    Enumeration E = Cats.elements ();
    while (E.hasmoreelements ()) ((CAT2) e.nextelement ()). print (); Dog is detected only at Run-time}}///:~ 


The only change we see is the last few lines. No longer:

for (int i = 0; i < cats.size (); i++)
(Cat) Cats.elementat (i)). Print ();

Instead, traverse the entire sequence with a enumeration:

while (e.hasmoreelements ())
(CAT2) e.nextelement ()). print ();

Using enumeration, we don't have to care about the number of elements in the collection. All work was automatically supervised by hasMoreElements () and Nextelement ().
Here's another example, let's create a general purpose Print method:
 

: Hamstermaze.java
//Using An enumeration
import java.util.*;

Class Hamster {
  private int hamsternumber;
  Hamster (int i) {
    hamsternumber = i;
  }
  Public String toString () {return ' This is
    hamster # ' + hamsternumber;
  }
}

Class Printer {
  static void Printall (enumeration e) {while
    (e.hasmoreelements ())
      System.out.println (
        e.nextelement (). toString ());
  }

public class Hamstermaze {public
  static void Main (string[] args) {
    vector v = new vector ();
    for (int i = 0; i < 3; i++)
      v.addelement (New Hamster (i));
    Printer.printall (V.elements ());
  }
///:~


Study the printing method carefully:

static void Printall (enumeration e) {while
  (e.hasmoreelements ())
    System.out.println (
      e.nextelement ( ). ToString ());

Note that there is no information associated with the sequence type. Everything we have is enumeration. To understand the sequence, a enumeration is sufficient: The next object can be obtained, and it is also known whether the end is reached. Taking a series of objects and then traversing them to perform a specific operation-a valuable programming concept that is used in many parts of this book.
This seemingly special example can even be more generic, because it uses the normal ToString () method, which is called a regular because it belongs to part of the object class. The following is another way to invoke printing (although it may be less efficient):
System.out.println ("" + e.nextelement ());
It uses the "automatic conversion to string" technology encapsulated into the Java interior. Once the compiler encounters a string, followed by a "+", you will want to follow a string followed by automatically calling ToString (). In Java 1.1, the first string is unnecessary, and all objects are converted to strings. You can also perform a styling on this to get the same effect as calling ToString ():
System.out.println ((String) e.nextelement ())
But what we want to do is usually not just call the object method, so we face the problem of type modeling again. For the type of interest you have, you must assume that you have obtained a enumeration, and then shape the resulting object into that type (if the operation is wrong, you will get a run-time violation).

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.