问题:为什么这里的代码是:Object y=x.remove();从队列中移除对象?这不是一个可变的任务吗。当我们没有调用它的时候,它为什么要运行代码?变量减速也会调用这些方法吗?
Queue<Integer> x = new LinkedList<Integer>();
x.add(5);
x.add(7)
Object y=x.remove(); //<------THIS
x.add(4)
System.out.println(x.element());
发布于 2017-08-12 05:52:51
在=的右边有一个表达式。计算该表达式,并将结果赋值给左侧的变量。
在您的示例中,该表达式由方法调用组成。对remove()的调用返回已删除的对象。准确地说,该方法删除了添加到队列中的第一个元素。
这就是一切。
发布于 2017-08-12 05:56:45
从方法的文档化本身来看,它非常清楚它在做什么:
/**
* Retrieves and removes the head of this queue. This method differs
* from {@link #poll poll} only in that it throws an exception if this
* queue is empty.
*
* @return the head of this queue
* @throws NoSuchElementException if this queue is empty
*/
E remove();尝试运行您的代码以查找详细信息:
x.add(5):->5 x.add(7);-> 5,7 y=x.remove();-> 7,y=5 x.add(4);-> 7,4 System.out.println(x.element());->打印7(此时头部不移除)
发布于 2017-08-12 06:29:11
您正在调用队列类的方法(.remove())。该方法删除队列的第一个元素并返回它。如果要检查队列的第一个元素而不删除它,可以使用peek方法( Object y=x.peek( );)。
https://stackoverflow.com/questions/45646928
复制相似问题