关于问题的Java基础知识

时间:2017-08-12 05:42:34

标签: java queue

问题 为什么这个代码在这里: 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());

3 个答案:

答案 0 :(得分:2)

在=的右边你有一个表达式。评估该表达式,并将结果分配给左侧的变量。

在您的情况下,表达式包含方法调用。对remove()的调用返回被删除的对象。然后将其分配给y。确切地说:该方法删除了添加到队列中的第一个元素。

这就是全部。

答案 1 :(得分:1)

documentation of the method本身来看,它非常清楚它在那里的作用:

/**
 * 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
Object y=x.remove(); --> 7, y=5
x.add(4); --> 7,4
System.out.println(x.element()); --> Prints 7 (head without removing this time)

答案 2 :(得分:0)

您正在调用队列类的方法(.remove())。此方法删除队列的第一个元素并返回它。如果要检查队列的第一个元素而不删除它,可以使用peek方法(Object y = x.peek();)。