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



我有以下代码:

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

最新更新