java - 为什么我的 Java 代码中会出现此输出?

标签 java stack queue implementation

The student at the top of the stack is Gullion,Hailey

Student Mcglothlen,Shizue is removed from the stack


Here are all the elements of the Stack using an Iterator
--------------------------------------------------------
Stack$Node@3012db7c
Stack$Node@2607c28c
Stack$Node@477588d5
Stack$Node@756a7c99
Stack$Node@221a5d08
Stack$Node@70d1c9b5
Stack$Node@5d11c3f0
Stack$Node@3956f14c
Stack$Node@7afbd1fc
null


Here are all the elements in the Stack
--------------------------------------
Putney,John
Larkey,Ismael
Winkler,Isiah
Aceto,Liana
Hamill,Crissy
Caraway,Elmira
Gullion,Hailey
Rodrigez,Jonie
Madruga,Terrell
Williams,Diego

使用迭代器的堆栈的第一个元素列表显然不起作用。我不知道为什么。这是我的 Stack 类中的 Iterator 代码:

public Iterator<Student> iterator()  { return new ListIterator();  }

// an iterator, doesn't implement remove() since it's optional
private class ListIterator implements Iterator<Student> {
    private Node<Student> current = top;

    public boolean hasNext()  { 
        return current != null;                     
    }

    public void remove() { 
        throw new UnsupportedOperationException();  


    @SuppressWarnings("unchecked")
    public Student next() {
        if (!hasNext()) throw new NoSuchElementException();
        current = current.next; 
       return (Student)current;
    }
}

这是我的 Driver 类中似乎存在问题的代码:

System.out.println("\nHere are all the elements of the Stack using an Iterator");
  System.out.println("--------------------------------------------------------");
  Iterator <Student> iter = myStack.iterator();
  while (iter.hasNext() )
      System.out.println(iter.next() );

这是所有类(class):

堆栈:http://pastebin.com/2HVLVHuM

队列类:http://pastebin.com/3q537kHW

学生类(class):http://pastebin.com/UnBB7kPA

驱动程序类别:http://pastebin.com/yeA34MNd

我只能在 Stack 类中编写代码。这样做的目的是使用队列实现堆栈。希望这有帮助

最佳答案

您需要在 Student 类中添加一个 toString() 方法。迭代器工作正常,但 System.out.println() 不知道如何显示 Student

Student 类中添加一些内容,如下所示...

public String toString(){
    return name;
}

这样当你调用System.out.println()时,它就可以输出一个真实的值。当您调用 System.out.println(Object) 时,它总是尝试输出 toString() 值。如果未定义此方法,它将输出对象的 java ID,这就是您所看到的。

关于java - 为什么我的 Java 代码中会出现此输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12966285/

相关文章:

java - 在java中将时间插入mysql数据库

algorithm - 计算范围的数量[L; R] 最大值与最小值之差为偶数

php - Laravel:运行队列:在 Windows Azure Web App 上连续监听

c - 将结构插入队列时出现段错误

spring - 使用 Spring Batch 或 Quartz 调度程序来调度作业

java - 从 Spring Boot 资源执行和处理 Void @Async 操作

java - 如何将多个大文件流式传输到 jetty

c - __interceptor_strchr 是做什么的?

c - 是否允许编译器通过重新排序局部变量来优化堆栈内存使用?

java - 如何使用 NetBeans 修改/添加代码到 Java 中的 initComponents() 方法?