从文件读取时如何添加到 Java LinkedList?

How to add to Java LinkedList while reading from a file?

我有以下代码:

public static void main(String args[]) {

int maxSize = 10; 
LinkedList<someObject> fifoList = new LinkedList<someObject>();
int item = 0; 
int p = 0; 

try {
    scanner = new Scanner(myFile);
    while(scanner.hasNextLine()) {

        String line = scanner.nextLine();
        item = Integer.parseInt(line);
        
        if(p == 0)
        {
            someObject myObj = new someObject(); 
            //if the linked list is empty, add the item to the head of list
            if(fifoList.isEmpty()){
                myObj.setItem(item);
                fifoList.add(myObj);
            }
            else{
                //as long as the size of the list is less than maxSize
                int pointer = 0; 
                if(fifoList.size() < p0Frames){
                    //if the item is not already in the list:
                    if(fifoList.get(pointer).getItem() != item){
                        myObj.setItem(item);
                        fifoList.add(myObj);
                    }
                }
                pointer++;
            }
        }               
    }
}
catch(FileNotFoundException e) {
    System.out.println("File was not found");
    e.printStackTrace();
}

for(someObject node: fifoList){
    System.out.println(node.getItem());
}

}

我有一个包含以下元素的文件:

13
13
13
13
13
14
14
19
17
17
17
18
17

输入此文件后,我希望我的 LinkedList 包含 13、14、19、17、18。但是,当我打印出来时,它会打印

13, 14, 14, 19, 17, 17, 17, 18, 17

为什么我的逻辑只检测第一个数字 (13) 的重复项,而忽略随后出现的所有重复项?我还检查了指针的值,它从未改变,所以我猜这也是导致此问题的错误。但是,我已经处理了几个小时,无法真正弄清楚如何解决它。任何帮助将不胜感激。

检测重复的逻辑需要fifoList中的元素循环,目前pointer的值对于每个元素都重置为0,因此只检查第一个值,因此以下所有不等于 13 的值都已成功添加。

代码可能固定如下:

someObject myObj = new someObject(); 
//if the linked list is empty, add the item to the head of list
if(fifoList.isEmpty()){
    myObj.setItem(item);
    fifoList.add(myObj);
}
else if (fifoList.size() < p0Frames) {
    //as long as the size of the list is less than maxSize
    boolean found = false; // flag if fifoList contains the item
    for (int i = fifoList.size() - 1; i >= 0  && !found; i--) {
        if(fifoList.get(i).getItem() == item) {
            found = true;
        }
    }
    if (!found) { // add missing value
        myObj.setItem(item);
        fifoList.add(myObj);
    }
}

输出:

13
14
19
17
18