gpt4 book ai didi

java - Java LinkedStack 实现中 ToString 方法的问题

转载 作者:行者123 更新时间:2023-11-30 07:45:15 26 4
gpt4 key购买 nike

我对这项作业有一个小问题:我打算完成 LinkedStack 实现并确保 peek、isEmpty 和 size 方法按照 Stack 接口(interface)中的定义实现。我相信我的大部分工作都正常(虽然还没有测试过),但我在 ToString 方法中遇到了一个障碍

这是讲师提供的启动

public interface Stack<T> {
/**
* Adds the specified element to the top of this stack.
* @param element element to be pushed onto the stack
*/
public void push(T element);
/**
* Removes and returns the top element from this stack.
* @return the element removed from the stack
*/
public T pop();
/**
* Returns without removing the top element of this stack.
* @return the element on top of the stack
*/
public T peek();
/**
* Returns true if this stack contains no elements.
* @return true if the stack is empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this stack.
* @return the number of elements in the stack
*/
public int size();
/**
* Returns a string representation of this stack.
* @return a string representation of the stack
*/
public String toString();}

这是我的 LinkedStack 类代码:

public class LinkedStack<T> implements Stack<T> {
private Node head; //the head node
private int size; // number of items


private class Node {
T item;
Node next;
}


public LinkedStack() {
head = null;
size = 0;

}

public boolean isEmpty() { return (size == 0); }


public T pop() {
T element = head.item;
head = head.next;
size--;

return element;
}


public void push(T element) {
Node oldHead = head;
head = new Node();
head.item = element;
head.next = oldHead;
size++;
}

public int size() { return size; }


public T peek() {
if (isEmpty()) throw new NoSuchElementException("Error: Stack underflow");
return head.item;
}

public String toString() {
StringBuilder string = new StringBuilder();
for (T stack : this) {
string.append(stack + " ");
}
return string.toString();
}}

由此我得到错误for-each 不适用于表达式类型 必需:数组或java.lang.Iterable 找到:edu.csuniv.isiahjohnson.LinkedStack

我是否需要一个用于堆栈项的 Iterator 对象,或者这仅适用于 LinkedList 类?

最佳答案

如果你想在java中使用foreach循环,你的对象需要实现Iterable接口(interface)。

在java中,这段代码:

for (T stack : this) {
...
}

是一个语法糖:

for(Iterator<T> iter = this.iterator(); iter.hasNext(); ) {
T item = iter.next();
...
}

很明显,您需要 iterator() 来做到这一点,因此 - 实现 Iterable

关于java - Java LinkedStack 实现中 ToString 方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34030546/

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