# of elements in an enumeration?

Hi there!
Does any of you know a way to count the number of elements in an enumeration without iterating through them?
Thanks in advance!

Can't be done. You could create a class that implements Enumeration and does the counting but you still end up iterating through the enumeration. It's just abstracted.

Similar Messages

  • How to disable the specific elements in the enumerator by other enumerator functions

    Hi,
    I have three enumerator functions.
    If I select the 1st enumerator first element then 2nd enumerator function top two elements should disable.
    If I select the 1st enumerator second element then 2nd enumerator function 3rd and 4th elements should disable.
    If I select the 1st enumerator third element then 3rd enumerator function top two elements should disable.
    thanks.
    with regards and warm welcome,
    Ramamoorthy S

    Hi
    i attached a sample vi that shows the concept. you can develop it into the actual logic that you want, with Enum 1, 2 and 3.
    post your code if need more help.
    Attachments:
    enum elements disable.vi ‏11 KB

  • Node removing in a Tree, for loop, and Enumeration

    Hi there
    it should be pretty easy, however i'm stuck with this code:
    public void supprNode(DefaultMutableTreeNode node){
    for(en = node.preorderEnumeration();e.hasMoreElements();){
    DefaultMutableTreeNode tmpNode= (DefaultMutableTreeNode) en.nexElement();
    if (tmpNode instanceof myderivedNodeClass)
        tmpNode.doSomething();
    if(!tmpNode.isRoot())
        removeNodeFromParent(tmpNode);
    }The problem is, the for loop doesn't traverse all the elements. That's if i call removeNodeFromParent. Is the enumeration updated twice?
    ie if my tree is
    root
    -1
    -2
    -3after the call of supprNode(root) i get:
    root
    -2And i really don't understand why.

    Hi!
    If you look at the apidoc of DefaultMutableTreeNode.preorderEnumeration() you will see following text:
    * Modifying the tree by inserting, removing, or moving a node invalidates
    * any enumerations created before the modification.
    So you should copy the elements of the enumeration in a separate list and iterate then over this list!
    With kind regard,
    Mathias

  • How to understand the Vector source code for function elements()?

    hello all:
    This following code snippet is extracted from java.util.Vector source code.
    who can tell me how i can understand what the function nextElement does?
    thank you
    public Enumeration elements() {
         return new Enumeration() {
             int count = 0;
             public boolean hasMoreElements() {
              return count < this.num_elem;
             public Object nextElement() {
              synchronized (Vector.this) {   //???
                  if (count < elementCount) {//???
                   return elementData[count++];
              throw new NoSuchElementException("Vector Enumeration");
        }

    Perhaps code would help more. This codeimport java.util.Vector;
    import java.util.Enumeration;
    import java.util.Iterator;
    public class Test {
        public static void main(String[] arghs) {
         Vector v = new Vector();
         Integer two = new Integer(2);
         // Fill the Vector
         v.add("One");
         v.add(two);
         v.add(new StringBuffer("Three"));
         // Enumerate through the objects in the vector
         System.out.println("---- Enumeration ----");
         Enumeration e = v.elements();
         while (e.hasMoreElements()) System.out.println(e.nextElement());
         // Loop through the objects in the vector
         System.out.println("---- Loop ----");
         for (int i=0; i<v.size(); i++) System.out.println(v.get(i));
         // Iterate through the objects in the vector
         System.out.println("---- Iterator ----");
         Iterator i = v.iterator();
         while (i.hasNext()) System.out.println(i.next());
    }produces this output
    ---- Enumeration ----
    One
    2
    Three
    ---- Loop ----
    One
    2
    Three
    ---- Iterator ----
    One
    2
    Three
    So, for a Vector, all three do the same thing. However, Iterator is part of the Collection Framework (see [url http://java.sun.com/j2se/1.4.2/docs/guide/collections/index.html]here). This allows you to treat a whole bunch of [url http://java.sun.com/j2se/1.4.2/docs/guide/collections/reference.html]objects which implement the Collection interface all the same way. I know this is way more than you were asking, but I hope it at least clears up what you were asking.

  • Java.util.Enumeration

    Hi all,
    java.util.Enumeration is an interface.
    but we are able to execute the methods (hasMoreElements, nextElement )defined in this interface.
    say for ex:
    java.util.Enumeration en =
    /* (Some code which returns Enumeation say :*/ Hashtable.keys();
    whithout the implementation , we are executng the methods defined in the Enumeration interface. how this is possible?
    thanks in advance.
    dhanasekaran.

    hi,
    I posted the code for the method elements from java.util.Vector which returns an Enumeration. This should explain your problem:public Enumeration elements()
         return new Enumeration() {
             int count = 0;
             public boolean hasMoreElements() {
              return count < elementCount;
             public Object nextElement() {
              synchronized (Vector.this) {
                  if (count < elementCount) {
                   return elementData[count++];
              throw new NoSuchElementException("Vector Enumeration");
    }greetings,
    Stijn

  • Enumeration never reaches nextElement(), goes into infinite loop

    String key = "";
    while (request.getSession().getAttributeNames().hasMoreElements()) {
      key = (String) request.getSession().getAttributeNames().nextElement();
      out.println("key = " + key + " and its value = " + (String) request.getSession().getAttribute(key) + "<P>");
    }This results in an infinite loop where key is the same first element while the Enumeration never advances.
    Why would this happen? Any ideas?
    Thanks

    Why would this happen? Any ideas? Your code obtains a fresh enumeration with each loop. Don't. Just use the same enumeration. Example:
    Enumeration e = request.getSession().getAttributeNames();
    while (e.hasMoreElements()) {
      String key = (String) e.nextElement();
      out.println("key = " + key + " and its value = " + (String) request.getSession().getAttribute(key) + "<P>");
    }~

  • A question about Enumeration()

    i am a beginner in java,resently i met a question about Enumeration(),and i hope someone can help me.
    my question is that in the package of java.util there is an interface called Enumeration and there are two method hasMoreElements()��nextElemen() in it.
    but in general we do not realize them before we use them.for example:
    first we defined a new class Vector
    Vector myVector = new Vector();
    then when after we add some objects to it,we can do like this:
    Enumeration e = myVectior.elements();
    e.nextElemen();
    i want to know where the method nextElemen is realized? incording to java's grammar,it is impossible to be realized in Enumeration for it is an interface,but
    both class Vector and the my own class do not realize it too.so i am confused.

    The class that implements the Enumeration returned by elements is hidden in the Vector class implementation. In fact, the class is anonymous. Here's the code from java.util.Vector (JDK 1.4).
       public Enumeration elements() {
            return new Enumeration() {
                int count = 0;
                public boolean hasMoreElements() {
                    return count < elementCount;
                public Object nextElement() {
                    synchronized (Vector.this) {
                        if (count < elementCount) {
                            return elementData[count++];
                    throw new NoSuchElementException("Vector Enumeration");
        }

  • Enumeration

    Is there any method (i mean, function) by which one can check whether a given value is in the
    enumeration. I want to avoid looping through all the elements of the enumeration and doing compare.
    Thanks

    Class "Properties" implements "Maps", so I can get a "Set" out of it !!
    Hmmm... I guess I need to THINK DEEPER. Thanks for ur response.
    btw, how many yrs of experience do you have ? Just curious to know when
    I will be ready to help out folks in this forum :)

  • Enumeration , class

    I have this following code in my JSP
    Enumeration en = session.getAttributeNames();
    System.err.println("Enumeration is "+en.getClass());
    gives me "java.util.Vector$1"
    Why does it show vector, a lit confused
    TIA

    Enumeration is an interface.
    java.util.Vector$1 is the class that is actually implementing the Enumeration interface.
    It is not actually a Vector. The $1 means that this class is actually an anonymous inner class of Vector.
    This is the code out of the Vector class that provides the enumeration.
    public Enumeration elements() {
         return new Enumeration() {
             int count = 0;
             public boolean hasMoreElements() {
              return count < elementCount;
             public Object nextElement() {
              synchronized (Vector.this) {
                  if (count < elementCount) {
                   return elementData[count++];
              throw new NoSuchElementException("Vector Enumeration");
        }So you actually do have an object that implements the enumeration interface. It is just an anonymous inner class written inside the Vector class, so its classname displays as java.util.Vector$1.
    Does that clear things up?
    Cheers,
    evnafets

  • Enumeration---methods implementation

    for handling vector elements,we use enumeration interface.normally
    one interface can have the sign of the methods only.but for handling
    the vector,we use the methods nextElement() and hasMoreElements()
    methods which are declared in enumeration interface.
    my question is where such methods of enumeration are implemented.

    they must be implementd in Vector, otherwise Vector would not compile

  • JMS QueueBrowser returns void enumeration

    It seems that oc4j 9.0.3 is not returning correctly the queue elements via QueueBrowser.getEnumeration(). The enumeration has no elements even when the queue has many of them. Here it is a code snippet:
    Context context = new InitialContext();
    // Lookup the managed connection factory for a Queue
    QueueConnectionFactory queueFactory = (QueueConnectionFactory)context.lookup("java:comp/env/jms/BgPrintQueueFactory");
    // Create a connection to the JMS provider
    QueueConnection queueConnection = queueFactory.createQueueConnection();
    queueConnection.start();
    // Create a Queue session
    QueueSession session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    // Lookup the destination you want to publish to
    Queue queue = (Queue)context.lookup("java:comp/env/jms/BgPrintQueue");
    // Create a browser
    QueueBrowser qbrowser = session.createBrowser(queue);
    // get elements in queue
    Enumeration enum = qbrowser.getEnumeration();
    Am I doing something wrong or is there any problem with the oc4j classes implementing the queue or the browser? If so, any alternative to plug an external QueueBrowser into oc4j?
    Thanks,
    Modulab

    I am using oc4j 9.0.3 and running the lightweight oc4j JMS implementation.
    The following post on the general Oracle 9iAS forum seems to suggest there are some jms features not implemented in the lightweight jms implementation:
    Re: Oracle Light weight JMS & Oracle9iAS 9.0.4
    1.Is the QueueBrowser one of these non-implemented features?
    2.If so, is oc4j9.0.4 fixing it and when is it to be released? (I expect something less vague than "later that year").
    3.Is the lightweight implementation documented? How can I know which features are running ok and which aren't?
    Thanks,
    Modulab

  • Comparing values of enumeration

    can any body plz tell me how should i comapire values in enumeration
    while(enuJob.hasMoreElements()){
    jobFBean = (jobFlowBean)enuJob.nextElement();
    this is my loop
    n i want to compaire one value in tht with the next value of enumeration??
    I think this code is used for that
    for(out=nElems-1; out>1; out--)
    for(in=0; in<out; in++)
    if( a[in] >a[in+1] )
    swap(in, in+1);
    } But how can i find the length of enumeration here out=nElems-1??

    can any body plz tell me how should i comapire values
    in enumeration
    while(enuJob.hasMoreElements()){
    jobFBean =
    (jobFlowBean)enuJob.nextElement();
    this is my loop
    n i want to compaire one value in tht with the next
    value of enumeration??
    I think this code is used for that
    for(out=nElems-1; out>1; out--)
    for(in=0; in<out; in++)
    if( a[in] >a[in+1] )
    swap(in, in+1);
    But how can i find the length of enumeration here
    out=nElems-1??Enumerations are designed to iterate over members of a collection and operate on each member separately, they aren't really meant for operating on the collection as a whole (such as swaping the positions of elements). I can show you how to compare two adjacent elements, but it wouldn't do you any good, because you don't have random access to elements in an enumeration. You can't do a swap operation.
    What you would want to do is have a simple, 1 element cache that stores the previous element, so you could do this:
    Object oldObject = enu.nextElement();
    while (enu.hasMoreElements()) {
        Object ofInterest = enu.nextElement();
        // I can do what ever I need to do to compare the two elements here.
        // here, I rotate out the oldObject and ofInterest
        oldObject = ofInterest;
    }Again, I don't see that doing you any good, because you can't modify the collection from the Enumeration. You need to have the actual collection object to do that.
    - Adam

  • Down Casting a Enumeration

    I tried the following code snippet.
    import java.util.*;
    class Strings implements Enumeration {
    public boolean hasMoreElements() { return false;}
    public Object nextElement() {return null;}
    public class MainClass
    public static void main(String args[])
    Vector VectorObj = new Vector();
    VectorObj.add("One");
    VectorObj.add("Two");
    VectorObj.add("Three");
    Strings StringObj = (Strings) VectorObj.elements();
    It compiles properly but i get the following run time exception:
    java.lang.ClassCastException: java.util.Vector$1
    what could be the problem? Do i need to do anything extra for the downcast?
    TIA,
    Babu

    Had a look into the implementation of Vector.elements(). The inner class in elements() was causing the problem.
    public Enumeration elements() {
    return new Enumeration() {
    int count = 0;
    public boolean hasMoreElements() {
    return count < elementCount;
    public Object nextElement() {
    synchronized (Vector.this) {
    if (count < elementCount) {
    return elementData[count++];
    throw new NoSuchElementException("Vector Enumeration");
    Thanks,
    Babu

  • Zipped files created with Java won't unzip with Java

    Hello there,
    I have written a class for unzipping a zip file using the 'ZipFile' class. It works perfectly fine when I extract zip files that have been created with XP, Winzip, or Winrar.
    I am now experimenting with creating zip files using the ZipOutputStream (http://forum.java.sun.com/thread.jspa?forumID=256&threadID=366550 by author smeee). The code works great for creating the zip file, but when I try and unzip it with the zipfile class mentioned above it throws an exception.
    The error that the following code gives me when it tries to convert an element from the enumeration to a ZipEntry is this: java.io.FileNotFoundException: C:\testfiles\out\high\BAUMAN\00001.jpg (The system cannot find the path specified)
    NOTE: The file is there by the way!!! :-)
    See the code for extracting here:
    try {
                 zippy = new ZipFile(fileName);
                 Enumeration all = zippy.entries();
                 while (all.hasMoreElements()) {//loop through all zip entries
                              getFile((ZipEntry)all.nextElement()); <<<=====FAILS HERE
    } catch (IOException err) {
                 System.err.println(err.toString());
                 return;
    }Now if I extract the zip file with winzip, then rezip it with winzip and run the above method again it works with no errors. Any thoughts. Any help would be greatly appreciated.
    Jared

    Hello All,
    For anyone else who use the forum posting by smeee as a guide to create a zipper (http://forum.java.sun.com/thread.jspa?forumID=256&threadID=366550 by author smeee).
    I was tracing through the code and found that there is a statement that adds 1 character (strSource.length()+1) to the source path. This was causing the following bug:
    In windows it was placing objects like this \myfolder\myfile.txt
    In unix it was placing objects like this yfolder\myfile.txt
    Naturally a path like \myfolder... in the zip index was causing problems. I have added a case statement that tests the OS and then adds two chars if windows to compensate for the 'C:' and does nothing if Unix. The code now runs perfectly on either OS.
    Thanks for your response guys!
    Jared

  • Trying to Understand Interfaces

    Hi all,
    As you might expect, I am new to JAVA. I have read the basics tutorial on interfaces and also the object oriented programming basics tutorial. I understand that you can't implement methods or variables in interfaces, etc. Here is what I am struggling with:
    A friend has written a class that uses the JNDI classes to query an LDAP service for person information and update database information. I notice that the query returns an object of type NamingEnumeration. But this is an interface, not a class. When he gets the items/elements from the Enumeration, he uses a (Attributes) to cast the results to their proper type.
    So, if I am writing a class and want to implement the NamingEnumeration interface over my class... and if I want to retrieve that class by its NamingEnumeration interface, rather than its actual class...how would I create a method that does this.
    My first attempt at creating this class went like this:
    public class DocumentEnumeration extends DocumentCollection implements NamingEnumeration
    If I called the .next method of my class, I would return a type Document. So far I don't know how to retrieve this DocumentEnumeration as a NamingEnumeration, and I received an error in my IDE about the constructor with arguments () is not visible. I did not understand this error either.
    Any help would be appreciated,
    Jeff

    DrClap's responses are all correct and to the point. Let me add a preface. Forget everything you've read, close your eyes and say "interfaces are dead simple!" about a hundred times. They are.
    An interface is a bundle of related capabilities. For example, I am a male homo sapiens (my class). I ski and play tennis - these are things I can do. As a Skier I have methods like buckleBoots(), getOnLift(), getOffLift() and skiDownHill(). All skiers implement these methods.
    TennisPlayers implement a different set of methods: serve(), volley() and so on. Some TennisPlayers may also implement Skier and some Skiers may implement TennisPlayer, but if an object of class LiftAttendant is going to call our getOnLift() method, it doesn't care about serve() or volley(). It knows that we have the handful of methods that concern LiftAttendants.
    Note that many different classes can implement an interface. Certainly some female homo sapiens implement Skier. I've also seen some apes and hot dogs implementing Skier.
    The Runnable interface defines just one method: public void run(). A Runnable is any class that claims it implements Runnable. If the class declaration claims that it implements Runnable, the compiler won't generate a .class file unless the class defines a public void run() method. When you pass a Runnable to a Thread, the Thread knows exactly one thing about the Runnable, that it has a public void run() method which the Thread can call after it is started. The Thread has no clue what it might be running, but because the object is a Runnable it can correctly call whatever.run().
    Why might a well-written method return an Interface type, not a class? Generality. The LiftAttendant need only know that an object has a getOnLift() method. So anything the implements Skier will be fine for the LiftAttendant.
    So an interface defines a set of methods (as few as one) that, taken together, constitute a capability. A class that implements these methods can claim to implement the interface, and other objects that care about that capability can say they work with Skier, or Runnable or whatever, so that they can handle lots of different things, not worrying about all the other things their Objects might implement or be.
    Very simple. Very powerful.

Maybe you are looking for

  • Windows 8.1 dual boot rEFInd

    Hi Everyone, Here's what I have done with my Intel NUC. I have a 480 GB mSATA SSD and 1 TB 2.5" SATA HDD and this is my partition layout NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sda 8:0 0 931.5G 0 disk └─sda1 8:1 0 931.5G 0 part sdb 8:16 0 447.1G 0 di

  • Payment method  EFT CB ISO - Full form

    Dear All, Kindly let me know the full form of standard Payment method configured for United Kingdom   *"5   - EFT CB ISO "" stands**

  • Can I Extract Video From A DVD I Made?

    I made a DVD in DVD SP 4. I no longer have the source video, but I wanted to extract some of the video from this DVD to make it into a Quicktime. Is that tough to do?

  • PSE 8 doesn't work after O/S upgrade

    I have used PSE 8 for some time on Windows XP. I recentl "upgraded" to Windows 7, and re-installed PSE 8. After some trouble finding my catalog, I got the organizer to work. However, when I try to switch to the editor, I get a message which says "Lic

  • XML removes tag while separating

    Hi, I have a XML doc LIKE this <ROWSET> <ROW> <P1> <ROWSET> <P1> ----table name <id>100</id> <FIRST_NAMEs3</FIRST_NAME> <LAST_NAME>s3</LAST_NAME> <P2> <ROWSET> <P2> <f1>1</f2> <b1> <ROWSET> <b1> <M>1060</M> </b1> </ROWSET> </b1> </P2> </p1> </ROWSET>