/**
* Created by unibodydesignn on 11.03.2017.
*/
public interface Enumeration
{
// Returns true if another element in the collection exists
public boolean hasNext();
// Returns the next element in the collection as an Object
public Object getNext(); }
/**
* NameCollection implements a collection of names using
* a simple array.
*/
public class NameCollection
{
String[] names;
//this array will be initiliazed at outside
NameCollection(String[] names)
{
this.names = names;
}
/**
* getEnumeration should return an instance of a class that
implements
* the Enumeration interface where hasNext() and getNext()
* correspond to data stored within the names array.
*/
Enumeration getEnumeration ()
{
}
public boolean hasNext()
{
//i will define this method here
}
public Object getNext()
{
//i will define getNext() here
}
完成 getEnumeration() 方法,以便它返回一个匿名内部类,该内部类与中的名称数组的 Enumeration 接口(interface)相对应 名称集合。然后编写一个创建NamesCollection的main方法 具有示例字符串数组的对象,通过以下方式检索此类的枚举 getEnumeration(),然后迭代输出每个枚举 使用 getNext() 方法命名。
我不明白这个问题的概念。我显然不知道该做什么或从哪里开始?我可以找到 Java 的默认 hasNext() 定义吗? 这不是家庭作业。 它是 Absolute Java 书中的一个编程项目。第 13 章 P3。
最佳答案
Complete the method
getEnumeration()
so that it returns an anonymous inner class that corresponds to theEnumeration
interface for the names array inNamesCollection
.
练习的目的似乎是使用匿名类。 例如,不要像这样创建一个命名类:
class NamesEnumeration implements Enumeration {
@Override
public boolean hasNext() {
// ...
}
@Override
public Object getNext() {
// ...
}
}
...说明指导您使用匿名类来代替,如下所示:
Enumeration getEnumeration() {
return new Enumeration() {
@Override
public boolean hasNext() {
// ...
}
@Override
public Object getNext() {
// ...
}
};
}
重要的一点是匿名实现可以使用在其范围内可见的变量。对于这个例子来说,最值得注意的是,
封闭的 NamesCollection
类的 names
字段。
在 NamesCollection
类中,
您不需要 hasNext
和 getNext
方法。
所以类应该看起来像这样:
public class NameCollection {
final String[] names;
NameCollection(String[] names) {
this.names = names.clone();
}
Enumeration getEnumeration() {
return new Enumeration() {
int currentIndex = 0;
// ^^^^^^^^^^^^ this is a hint for you
@Override
public boolean hasNext() {
// ...
}
@Override
public Object getNext() {
// ...
}
};
}
}
我做了一些小的改进,并添加了一个提示来帮助您完成实现。
最后,练习还要求添加一个 main
方法来练习此类。应该是这样的:
public static void main(String[] args) {
String[] sample = {"hello", "world"};
NameCollection namesCollection = new NameCollection(sample);
Enumeration names = namesCollection.getEnumeration();
while (names.hasNext()) {
System.out.println(names.getNext());
}
}
关于java - 从接口(interface)返回内部类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42731668/