【问题标题】:What is the use of the position interface in the Linked list implementations?链表实现中的位置接口有什么用?
【发布时间】:2016-11-21 14:12:07
【问题描述】:

我没有看到界面的使用, 为什么我们不能直接在Node类中直接实现getElement()方法呢?

public interface Position <T> {
public T getElement();
}

特此为 SNODE 类:

public class SNode<T> implements Position<T> {

private T element;
private SNode<T> next;

public SNode(T e, SNode<T> n) {
    element = e;
    next = n;
}

public SNode<T> getNext() {
    return next;
}

public void setNext(SNode<T> next) {
    this.next = next;
}

public void setElement(T element) {
    this.element = element;
}

@Override
public T getElement() {
    return element;
}
}

【问题讨论】:

  • 为什么需要这样做?
  • 如果只看类的声明/定义,那么你将看不到接口的使用。另一方面,在客户端代码中,您可以将SNode 传递给以Position 作为参数的方法。然后你会看到接口的“使用”,因为SNode 被“使用”为Position
  • 其实可以的。在java中你只能有1个超类,但你可以实现你想要的所有接口。如果您的案例以一个可以返回当前元素的 Node 类结束,则可以。
  • 您的问题的答案取决于如何使用此代码。

标签: java list linked-list singly-linked-list


【解决方案1】:

位置接口为结构中元素的位置提供了一般抽象。位置充当更广泛列表中的标记/标记。与列表 L 中的某个元素 e 相关联的位置 p 不会改变,即使 e 的索引 由于列表中其他地方的插入或删除,L 发生变化。如果我们用另一个元素替换存储在 p 中的元素 e,位置 p 也不会改变。位置变为无效的唯一方法是删除该位置。

定义位置类型的原因是允许位置作为某些方法的参数并从列表的其他方法返回值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2014-09-25
    • 1970-01-01
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多