英文:
Is my example a description for ADTs? (java)
问题
我理解ADT(抽象数据类型)可以隐藏/抽象方法的具体实现。那么,接口是一种ADT,对吗?所以我的问题是:
- 用于说明接口 MyStack 作为ADT以及在类 ImplementationOfMyStack 中实现的示例,是正确的吗?
- 如果问题1的答案是肯定的,那么为什么Java库中会有一个名为 Stack 的类?我感到困惑的是,我可以实例化 Stack 类,使用push()、pop()、peek(),而无需像我的示例中那样编写实现。因此,我认为 Stack 类有其实现,因此是一种数据结构而不是ADT。
public interface MyStack {
public void push();
public void pop();
public void peek();
}
public class ImplementationOfMyStack implements MyStack {
public void push() {
System.out.println("在此处编写将新项推入顶部的实现代码。");
System.out.println("实现是一种数据结构,例如链表。");
}
public void pop() {
System.out.println("在此处编写将顶部的项弹出的实现代码。");
System.out.println("实现是一种数据结构,例如链表。");
}
public void peek() {
System.out.println("在此处编写查看顶部的项的实现代码。");
System.out.println("实现是一种数据结构,例如链表。");
}
}
英文:
I understand that ADTs (abstract data types) hide/abstract the implementation of a method. So, an interface is an ADT, correct? So my questions are:
- Is my example to illustrate the interface MyStack as an ADT and its implementation in the class ImplementationOfMyStack, correct?
- If question 1 is yes, then why is there a class Stack in Java Libraries? My confusion is that I can instantiate the class Stack to use push(), pop(), peek() without coding an implementation like my example does. So, I think the class Stack has its implementation and is therefore a data structure and not an ADT.
public interface MyStack {
public void push();
public void pop();
public void peek();
}
public class ImplementationOfMyStack implements MyStack {
public void push() {
System.out.println("Code an implementation here to push a new item on top.");
System.out.println("The implementation is a data structure e.g. linked List.");
}
public void pop() {
System.out.println("Code an implementation here to pop a new item from top.");
System.out.println("The implementation is a data structure e.g. linked List.");
}
public void peek() {
System.out.println("Code an implementation here to peek a new item from top.");
System.out.println("The implementation is a data structure e.g. linked List.");
}
}
答案1
得分: 0
- 是的,接口是一个抽象数据类型。
- 你的实现是正确的。
- Java库中总是有一个Stack类。栈是一种通用数据结构,表示后进先出(LIFO)的对象集合,允许在常数时间内推入/弹出元素。(我建议使用Deque接口。Deque定义了一组更完整和一致的LIFO操作。)
英文:
- Yes an interface is an abstract data type.
- Your implementation is correct.
- There is always a Stack class in the java library. Stack is a generic data structure that represents a LIFO (last in, first out) collection of objects allowing for pushing/popping elements in constant time. (I would recommend to use the Deque interface. Deque defines a more complete and consistent set of LIFO operations.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论