-1
public static void main(String[] args) {

    ArrayList v1 = new ArrayList();
    v1.add(123);
    v1.add(153);
    v1.add(125);

    Enumeration en = v1.elements(); // This line gives error. 
    v1.add(4000);
    while(en.hasMoreElements())
    {
        System.out.println(en.nextElement());
    }

    System.out.println(v1);
}

Why there is an error in case of ArrayList but not in case of Vector?

Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50
  • 3
    Because, as [the documentation says](https://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html) "_New implementations should consider using `Iterator` in preference to `Enumeration`._" . And, from the [documentation for `Vector`](https://docs.oracle.com/javase/8/docs/api/java/util/Vector.html) "_it is recommended to use `ArrayList` in place of `Vector`._". Basically both things you mention are **deprecated** and **should not be used**. – Boris the Spider Nov 13 '17 at 21:01
  • 2
    Although indeed there have been preferred alternatives for a long time, @Boris, neither `java.util.Vector` nor its `elements()` method is formally deprecated. – John Bollinger Nov 13 '17 at 21:07
  • Whilst not formally deprecated - as in marked for removal - I argue that these are _effectively_ deprecated as the same recommendation not to use them in new code is given. – Boris the Spider Nov 14 '17 at 07:33

1 Answers1

1

Because Enumeration is a legacy class.
As the Vector class.
List and Collection more generally favor the use of Iterator to iterate on elements of them.
Iterator also provides a removal operation that Enumeration doesn't have.

You can read in the Enumeration javadoc :

NOTE: The functionality of this interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • I'm thinking it could be related to because of Enumeration supporting concurrency whereas arraylist being non-synchronized... – Anantanuj Dey Nov 13 '17 at 21:07
  • 1
    @AnantanujDey, `Enumeration` has no more or less support for concurrency than does `Iterator`. Moreover, though `Vector` is indeed synchronized and `ArrayList` isn't, that does not constitute a reason why `ArrayList` couldn't have provided the same interface as Vector. It's simply that Joshua Bloch and Sun decided to start fresh when they designed the Collections API. They eased the forward transition by retrofitting the old `Vector` and `Hashtable` classes, but they chose not to be constrained by those and related classes' and interfaces' forms. – John Bollinger Nov 13 '17 at 21:17
  • Thanx mate @JohnBollinger . I had some doubt, you cleared it :) – Anantanuj Dey Nov 13 '17 at 21:24