简体   繁体   English

LinkedList - addLast()并不总是在列表末尾添加值

[英]LinkedList - addLast() not always adding value at end of a list

I have to add an element at the end of a list so now I am using addLast() function of LinkedList to add element at the end. 我必须在列表的末尾添加一个元素,所以现在我使用LinkedList的 addLast()函数在最后添加元素。 It does add element in the list if and only if there is NO more add() statements after it. 当且仅当后面没有add()语句时,才会在列表中添加元素。

Below works fine. 下面工作正常。

LinkedList<String> ls = new LinkedList<String>();

    ls.add("C");
    ls.add("E");
    ls.add("D");
    ls.add("B");

    ls.addLast("F");            
    ls.addFirst("A");

    for( String l : ls )             
          System.out.println( l  );

And in the below case, it will not add item at the end of the list. 在下面的例子中,它不会在列表的末尾添加项目。

LinkedList<String> ls = new LinkedList<String>();

    ls.add("C");
    ls.add("E");
    ls.add("D");

    ls.addLast("F"); 
    ls.add("B");

    ls.addFirst("A");

    for( String l : ls )             
          System.out.println( l  );

However, addFirst() works fine regardless of place where you call it. 但是,无论您调用它的位置, addFirst()都可以正常工作。

How I can achieve this? 我怎么能做到这一点? any suggestion please. 任何建议请。

From java docs: 来自java文档:

public boolean add(E e)
Appends the specified element to the end of this list.
This method is equivalent to addLast(E).

Specified by:
add in interface Collection<E>
Specified by:
add in interface Deque<E>
Specified by:
add in interface List<E>
Specified by:
add in interface Queue<E>
Overrides:
add in class AbstractList<E>
Parameters:
e - element to be appended to this list
Returns:
true (as specified by Collection.add(E))

In your case the you add 'B' for the end of the list after you added 'F' to the end of the list 在您的情况下,在将“F”添加到列表末尾后,为列表末尾添加“B”

"it will not add item at the end of the list." “它不会在列表的末尾添加项目。”

Yes it will, it adds the item at the end of the current list. 是的,它会在当前列表的末尾添加项目。 What it won't do is keep it always last. 它不会做的就是让它永远持续下去。 Imagine what would happen if you did addLast() two times, which one would have priority? 想象一下,如果你做了两次addLast(),哪一个会有优先权会发生什么? Same thing with addFirst(), it only works on the current list, and if you add more firsts the other ones won't be first anymore. 与addFirst()相同,它只适用于当前列表,如果你添加更多第一,其他的将不再是第一个。

Specify the position of adding "B" for example ls.add(ls.size() - 1, "B"); 指定添加"B"的位置,例如ls.add(ls.size() - 1, "B"); Then "F" will be added in last. 然后在最后添加"F"

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

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