简体   繁体   English

为什么我在Java代码中得到此输出?

[英]Why I am getting this output in my Java code?

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

The first list of elements of the Stack using an Iterator apparently is not working. 使用迭代器的Stack的第一个元素列表显然无法正常工作。 I do not know why. 我不知道为什么。 Here is my code for Iterator in my Stack class: 这是我在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;
    }
}

Here is the code in my Driver class that is where there seems to be a problem: 这是我的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() );

HERE IS ALL OF THE CLASSES: 这里有所有的课程:

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

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

Student class: http://pastebin.com/UnBB7kPA 学生班: http//pastebin.com/UnBB7kPA

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

I CAN ONLY WRITE CODE IN THE STACK CLASS. 我只能在堆栈类中写代码。 The point of this was to Implement a stack using queues. 这样做的重点是使用队列实现堆栈。 Hope this helps 希望这可以帮助

You need to add a toString() method in your Student class. 您需要在Student类中添加toString()方法。 The Iterator is working correctly, but the System.out.println() doesn't know how to display the Student . 迭代器正常工作,但是System.out.println()不知道如何显示Student

Add something to the Student class like this... 像这样向Student班级添加一些内容...

public String toString(){
    return name;
}

So that when you call System.out.println() , it can output a real value. 这样,当您调用System.out.println() ,它可以输出一个实数值。 When you call System.out.println(Object) , it always tries to output the toString() value. 当您调用System.out.println(Object) ,它总是尝试输出toString()值。 If this method isn't defined, it will output the java ID of the object, which is what you're seeing. 如果未定义此方法,它将输出对象的java ID,即您所看到的。

First of all, see nneonneo 's answer for the incorrect cast in your next() method. 首先,请查看nneonneo的答案,以了解next()方法中的转换是否不正确。

Secondly, your Iterator implementation is incorrect. 其次,您的Iterator实现不正确。

The next() function in your iterator returns the element current after setting it to current.next . next()在你的迭代函数返回元素current将其设定为后current.next

After calling next() on the last element of your iteration, hasNext() should return false. 在迭代的最后一个元素上调用next()之后, hasNext()应该返回false。 But it doesn't, because current still points to the element you just returned. 但事实并非如此,因为current仍然指向您刚刚返回的元素。 So you will call next() again. 因此,您将再次调用next() And in this method, current = current.next will set current to null , and then return it. 在此方法中, current = current.next会将current设置为null ,然后将其返回。 Which should not happen, since hasNext was true, right? 既然hasNext是真实的,那应该不会发生,对吧?

For the same reason, the fist elemtent of your stack is missing: You set current to the top element of your stack, but before outputting anything, you already switch to current = current.next . 出于同样的原因,堆栈的第一要素也缺失了:您将current设置为堆栈的顶部元素,但是在输出任何内容之前,您已经切换到current = current.next You should do that after doing the output. 您应该在完成输出执行此操作。

current in your Stack iterator is defined as Node<Student> . currentStack迭代器被定义为Node<Student> You return current from your next() method using a cast. 您可以使用强制转换从next()方法返回current

So, next() returns a Node<Student> (type-cast to Student ), instead of an actual Student . 因此, next()返回一个Node<Student> (类型转换为Student ),而不是实际的Student Since Node presumably doesn't have a toString method, you get the default output ( Stack$Node@<addr> ). 由于Node可能没有toString方法,因此您将获得默认输出( Stack$Node@<addr> )。

To fix, return something like current.item from next() instead (assuming that the item stored in the Node is called item ). 要进行修复,请从next()返回类似current.item (假设存储在Node中的item称为item )。

The first list of elements of the Stack using an Iterator apparently is not working. 使用迭代器的Stack的第一个元素列表显然无法正常工作。 I do not know why. 我不知道为什么。

Because your iterator is returning a Node<Student> instead of a student. 因为您的迭代器正在返回Node<Student>而不是学生。 The problem is at: 问题出在:

return (Student)current;

You probably tried to do this, but got an Incompatible Type error: 您可能试图这样做,但是出现了Incompatible Type错误:

return current;

So you tried to fix by casting. 因此,您尝试通过投射进行修复。 The problem is that a node is not a student. 问题在于节点不是学生。 A node contains a student. 一个节点包含一个学生。 You need to return the student that the node contains. 您需要返回该节点包含的学生。

Try this: 尝试这个:

    return current.data;

No casting is required because the compiler knows that the "data" member of node is a Student, since you declared current of type Node<Student> . 不需要强制转换,因为编译器知道node的“数据”成员是Student,因为您声明的当前类型为Node<Student> This will fix the problem where your student prints out incorrectly. 这将解决您的学生打印错误的问题。 However as pointed out by @Konstantin, your iterator is still broken. 但是,正如@Konstantin指出的那样,您的迭代器仍然损坏。 You need to save the value of current in a temporary variable, move current, then return the temporary variable. 您需要将current的值保存在一个临时变量中,移动current,然后返回该临时变量。 Here is one possible implementation: 这是一种可能的实现:

    public Student next() {
        if (current == null) throw new NoSuchElementException();
        Node<Student> result = current;
        current = current.next;
        return result.data;
    }

[epilogue] [结语]

You really need to review the generics tutorial . 您确实需要查看泛型教程 It's not clear from the code you pasted in above but it's obvious in the paste-bin code that you are using Student as a type parameter. 从上面粘贴的代码尚不清楚,但在粘贴bin代码中很明显您正在使用Student作为类型参数。 That is very non-standard and confusing. 这是非常不标准和令人困惑的。 The convention is to use a capital letter - typically T. You should have declared stack like below. 惯例是使用大写字母-通常为T。您应该像下面这样声明stack。 Everywhere you use Student, replace it with T. 在所有使用Student的地方,都用T代替。

public class Stack <T> implements Iterable<T>{   // good

instead of 代替

public class Stack <Student> implements Iterable<Student>{ // bad

T means some type to be decided later and you can use Stack with any kind of object. T表示稍后要确定的某种类型,您可以将Stack与任何类型的对象一起使用。 Only when you actually create a stack to you use Student (or whatever) 仅当您实际创建堆栈时才使用Student(或其他任何方式)

public static void main(String [] args)
{
    Stack<Student> x = new Stack<Student>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM