Java中的接口列表?

Java中的接口列表?,java,interface,Java,Interface,我在做Leetcode的问题 原代码为: /** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * public interface NestedInteger { * * // @return true if this NestedInteger h

我在做Leetcode的问题

原代码为:

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public interface NestedInteger {
 *
 *     // @return true if this NestedInteger holds a single integer, rather than a nested list.
 *     public boolean isInteger();
 *
 *     // @return the single integer that this NestedInteger holds, if it holds a single integer
 *     // Return null if this NestedInteger holds a nested list
 *     public Integer getInteger();
 *
 *     // @return the nested list that this NestedInteger holds, if it holds a nested list
 *     // Return null if this NestedInteger holds a single integer
 *     public List<NestedInteger> getList();
 * }
 */
public class NestedIterator implements Iterator<Integer> {

    public NestedIterator(List<NestedInteger> nestedList) {

    }

    @Override
    public Integer next() {

    }

    @Override
    public boolean hasNext() {

    }
}

/**
 * Your NestedIterator object will be instantiated and called as such:
 * NestedIterator i = new NestedIterator(nestedList);
 * while (i.hasNext()) v[f()] = i.next();
 */
我意识到NestedIterator构造函数使用接口列表作为参数。我感到困惑,为什么它不在某处实现接口,而是直接在列表中使用它。我认为我们不应该直接使用界面。 谢谢

根据任务描述,您不应将其嵌套在集成中实现,也不应猜测其实现

在现实世界中,在使用之前,您必须声明接口并在某处实现它。然而,在这个简化的任务中,您只需要实现NestedIterator类。LeetCode负责以适当的方式实现NestedInteger——您只需仔细阅读NestedInteger实现说明并在代码中使用其方法

我感到困惑,为什么它没有在某个地方实现接口


确实如此。编译时,LeetCode将修改您的代码,例如,通过添加import some.package.NestedInteger,使其不会抛出编译错误。

接口允许抽象掉实现细节。使用代码不需要知道具体的实现,它只依赖于接口。然而,很明显,它的实施必须存在于某个地方。不能实例化接口


这就是接口的威力,直接使用它们是一种很好的做法。

在现实世界中,接口的实现是由另一个团队完成的。但是在这个简化的任务中,您只需要实现NestedIterator类。这是什么意思?NestedIterator是一个类,为什么我需要实现它?直接使用接口名在语法上正确吗?Implement不一定意味着Implement关键字。实现意味着为某些东西编写代码,有时意味着编写实现接口的代码。