Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

java - Why aren't Enumerations Iterable?

In Java 5 and above you have the foreach loop, which works magically on anything that implements Iterable:

for (Object o : list) {
  doStuff(o);
}

However, Enumerable still does not implement Iterable, meaning that to iterate over an Enumeration you must do the following:

for(; e.hasMoreElements() ;) {
  doStuff(e.nextElement());
}

Does anyone know if there is a reason why Enumeration still does not implement Iterable?

Edit: As a clarification, I'm not talking about the language concept of an enum, I'm talking a Java-specific class in the Java API called 'Enumeration'.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As an easy and clean way of using an Enumeration with the enhanced for loop, convert to an ArrayList with java.util.Collections.list.

for (TableColumn col : Collections.list(columnModel.getColumns()) {

(javax.swing.table.TableColumnModel.getColumns returns Enumeration.)

Note, this may be very slightly less efficient.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...