Search code examples
javacollectionsenumeration

retriving elements using enumeration


see the below code,I am retriving elements from vector and printing using enumeration.

package com.rajeev.enumeration;

import java.util.Enumeration;
import java.util.Vector;

public class Modification_On_Eumeration {
    public static void main(String[] args) {
        Vector<Integer> vector = new Vector<Integer>();
        vector.add(1);
        vector.add(2);
        System.out.println(vector);//here it is printing 12(ok)
        Enumeration<Integer> enumeration = vector.elements();
        while (enumeration.hasMoreElements()) {
            Integer integer = (Integer) enumeration.nextElement();
            System.out.print(integer);//why it is printing 123 instead of 12(reason ????)
        }
        vector.add(3);
        while (enumeration.hasMoreElements()) {
            Integer integer1 = (Integer) enumeration.nextElement();
            System.out.println(integer1);//why it is not printing ???
            System.out.println("why not printing");
        }
    }
}

output
------
[1, 2]
123
why not printing

the first while loop is printing elements of vector but the second while loop is not printing elements,why? and how the first while loop is able display 123 instead of 12 ? I am learning java help me ..


Solution

  • You are using only one Eumeration object in both while loops.

    The System.out.prinln(vector); line prints out [1, 2].

    The first while loop prints out 12, because those are the only 2 elements at that time.

    You add a third element, but you don't start over with a new Enumeration. The old Enumeration now sees another element, so it prints 3, on the same line. Both loops contribute to the single line of output, 123.

    It also explains why you see

    why not printing
    

    printed only once.