gpt4 book ai didi

java - 如何调用枚举的方法

转载 作者:行者123 更新时间:2023-11-30 10:57:34 25 4
gpt4 key购买 nike

Enumeration API

在 Enumeration API 中给出的示例中有以下示例:

for (Enumeration<E> e = v.elements(); e.hasMoreElements();)
System.out.println(e.nextElement());

但是当 Enumeration 是一个 iterface 时,如何在 vector 的元素上调用这些方法呢?
我的意思是这些方法没有主体(实现)?

最佳答案

Enumeration<E> e = v.elements();

这意味着 elements()方法返回一个实现 Enumeration 的类或返回 annonymous innerclass那个例子。

这里是Vector的源代码类(class) elements()方法

 public Enumeration<E> More ...elements() {
312 return new Enumeration<E>() {
313 int count = 0;
314
315 public boolean More ...hasMoreElements() {
316 return count < elementCount;
317 }
318
319 public E More ...nextElement() {
320 synchronized (Vector.this) {
321 if (count < elementCount) {
322 return elementData(count++);
323 }
324 }
325 throw new NoSuchElementException("Vector Enumeration");
326 }
327 };
328 }

如果您看到它正在返回 return new Enumeration<E>() {

关于java - 如何调用枚举的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32571037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com