LinkedList:getFirst()和getLast()指向同一元素的原因是什么?

huangapple go评论80阅读模式
英文:

LinkedList : Is there a reason that getFirst() and getLast() are pointing to the same element?

问题

在使用由Collections提供的LinkedList时,是否存在getFirst()和getLast()显示相同元素的情况?

我将数据解析到暂存变量中,然后将这些变量存储在新对象中,再使用add()方法将这些对象存储在我的LinkedList中。然而,在每次将对象添加到LinkedList后,通过使用getFirst()和getLast(),它们指向相同的对象。

请参见下面的代码(请不要过多批评代码,我只是一个初学者,所以我知道它不够优雅,但它重新创建了我的问题)。

public class Main {

    public static void main(String[] args) {
        Parse parse = new Parse();
        parse.main();
    }
}
import java.lang.reflect.Array;

public class Parse {
    String[] input = {"1", "a",
        "2", "b",
        "3","c",
        "4", "d"};

    Object tempObject = new Object();

    String tempLength;
    String tempFilename;
    int arrayIndex = 0;
    public static ObjectList objectList = new ObjectList();

    Parse(){
    }

    public void main() {

        for (int i = 0; i != input.length; i++) {
            String stringInput = iterateInputArray(input, i);
            addToTempObject(stringInput);

            Object finalObject = new Object();
            finalObject = tempObject;
            Object tempObject = new Object();

            objectList.addToList(finalObject);

            System.out.println("First:" + ObjectList.listOfObjects.getFirst());
            System.out.println("Last:" + ObjectList.listOfObjects.getLast());
        }
    }

    public String iterateInputArray(String[] input, int arrayIndex){
        String string = input[arrayIndex];
        return string;
    }

    private void addToTempObject(String inputString){
        if (tempLength == null){
            tempLength = inputString;
            tempObject.setLength(inputString);
        }
        else {
            tempObject.setFilename(inputString);
            tempFilename = inputString;
            resetTempVariables();
        }
    }

    private void resetTempVariables() {
        tempLength = null;
        tempFilename = null;
    }
}
public class Object {

    private String length;
    private String filename;

    public Object( String length, String filename) {

        this.length = length;
        this.filename = filename;
    }

    public Object(){
        this.length = null;
        this.filename = null;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public void setLength(String length) {
        this.length = length;
    }


    public String getLength() {
        return this.length;
    }

    public String getFilename() {
        return this.filename;
    }

}
import java.util.LinkedList;

public class ObjectList extends Object {
    public static LinkedList<java.lang.Object> listOfObjects = new
        LinkedList<java.lang.Object>();

    public ObjectList() {
    }

    public void addToList(Object object){
        listOfObjects.add(object);
    }
}
英文:

Are there any cases in which getFirst() and getLast() show the same element when using the LinkedList provided by Collections?

I am parsing data to staging variables to be held; then I am storing these variables in a new object to be stored in my LinkedList<Object> using the add() method. However, when I am printing out statements, after every time an object is added to my LinkedList, by using the getFirst() and getLast() they are pointing to the same object?

Please see code below (please dont critic the code too much, I am only a beginner so I know it isn't pretty, but it recreates my problem)

public class Main {
public static void main(String[] args) {
Parse parse = new Parse();
parse.main();
}
}

import java.lang.reflect.Array;
public class Parse {
String[] input = {&quot;1&quot;, &quot;a&quot;,
&quot;2&quot;, &quot;b&quot;,
&quot;3&quot;,&quot;c&quot;,
&quot;4&quot;, &quot;d&quot;};
Object tempObject = new Object();
String tempLength;
String tempFilename;
int arrayIndex = 0;
public static ObjectList objectList = new ObjectList();
Parse(){
}
public void main() {
for (int i = 0; i != input.length; i++) {
String stringInput = iterateInputArray(input, i);
addToTempObject(stringInput);
Object finalObject = new Object();
finalObject = tempObject;
Object tempObject = new Object();
objectList.addToList(finalObject);
System.out.println(&quot;First:&quot; + ObjectList.listOfObjects.getFirst());
System.out.println(&quot;Last:&quot; + ObjectList.listOfObjects.getLast());
}
}
public String iterateInputArray(String[] input, int arrayIndex){
String string = input[arrayIndex];
return string;
}
private void addToTempObject(String inputString){
if (tempLength == null){
tempLength = inputString;
tempObject.setLength(inputString);
}
else {
tempObject.setFilename(inputString);
tempFilename = inputString;
resetTempVariables();
}
}
private void resetTempVariables() {
tempLength = null;
tempFilename = null;
}
}

public class Object {
private String length;
private String filename;
public Object( String length, String filename) {
this.length = length;
this.filename = filename;
}
public Object(){
this.length = null;
this.filename = null;
}
public void setFilename(String filename) {
this.filename = filename;
}
public void setLength(String length) {
this.length = length;
}
public String getLength() {
return this.length;
}
public String getFilename() {
return this.filename;
}
}

import java.util.LinkedList;
public class ObjectList extends Object {
public static LinkedList&lt;java.lang.Object&gt; listOfObjects = new
LinkedList&lt;java.lang.Object&gt;();
public ObjectList() {
}
public void addToList(Object object){
listOfObjects.add(object);
}
}

答案1

得分: 0

我精简了代码精简后的代码在讨论问题时与提供的代码完全相同

    import java.util.LinkedList;
    
    class Scratch {
    
        public static final Object tempObject = new Object();
    
        public static void main(String[] args) {
            LinkedList<Object> list = new LinkedList<>();
            for (int i = 0; i != 10; i++) {
    
                list.add(tempObject);
    
                System.out.printf("First: %s, Last: %s, Size: %d%n",
                    list.getFirst(),
                    list.getLast(),
                    list.size());
            }
        }
    }

代码一直在将同一个对象 tempObject 添加到列表中。注意引入了 final 关键字,以突出变量 tempObject 在其整个生命周期内引用相同的对象。因此,列表的大小会增长,但列表中会重复包含相同的对象。这就是为什么 getFirst()getLast() 返回相同的对象。

问题可以通过将 tempObject 的声明移动到循环中来修复,例如:

import java.util.LinkedList;

class Scratch {

    public static void main(String[] args) {
        LinkedList<Object> list = new LinkedList<>();
        for (int i = 0; i != 10; i++) {
            final Object tempObject = new Object();
            list.add(tempObject);

            System.out.printf("First: %s, Last: %s, Size: %d%n",
                list.getFirst(),
                list.getLast(),
                list.size());
        }
    }
}
英文:

I reduced the code. The reduced code is, for the discussion of the prorblem, identical to the provided code:

import java.util.LinkedList;
class Scratch {
public static final Object tempObject = new Object();
public static void main(String[] args) {
LinkedList&lt;Object&gt; list = new LinkedList&lt;&gt;();
for (int i = 0; i != 10; i++) {
list.add(tempObject);
System.out.printf(&quot;First: %s, Last: %s, Size: %d%n&quot;,
list.getFirst(),
list.getLast(),
list.size());
}
}
}

<kbd>Ideone demo</kbd>

The code keeps adding one and the same object (tempObject) to the list. Notice the final keyword introduced to highlight that variable tempObject references the same object over its whole lifetime. Thus, the size of the list grows, but the list contains the same object, over and over again. This is why getFirst() and getLast() return the same object.

The problem can be fixed by, e.g., moving the declaration of tempObject in the loop:

import java.util.LinkedList;
class Scratch {
public static void main(String[] args) {
LinkedList&lt;Object&gt; list = new LinkedList&lt;&gt;();
for (int i = 0; i != 10; i++) {
final Object tempObject = new Object();
list.add(tempObject);
System.out.printf(&quot;First: %s, Last: %s, Size: %d%n&quot;,
list.getFirst(),
list.getLast(),
list.size());
}
}
}

<kbd>Ideone demo</kbd>

答案2

得分: -1

是的,一个只有一个元素的链表。就像下面的测试一样:

import static org.assertj.core.api.Assertions.assertThat

class ListSpec extends Specification{

    def "只有一个元素的链表"(){
        given: "一个只有一个元素的链表"
        LinkedList<String> list = new LinkedList<>();
        list.add("test");
        expect:"第一个和最后一个元素相同"
        assertThat(list.getFirst()).isEqualTo(list.getLast());
    }
}
英文:

yes, a linked list with one element. like following test

import static org.assertj.core.api.Assertions.assertThat
class ListSpec extends Specification{
def &quot;linked list with one elem&quot;(){
given: &quot;a linked list with one element&quot;
LinkedList&lt;String&gt; list = new LinkedList&lt;&gt;()
list.add(&quot;test&quot;)
expect:&quot;last and first element are same&quot;
assertThat(list.getFirst()).isEqualTo(list.getLast())
}
}

huangapple
  • 本文由 发表于 2020年8月17日 23:08:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63453635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定

  • 开发者交流平台

    本页二维码