需要搜索LinkedList中的对象元素

时间:2015-11-23 02:06:23

标签: java linked-list

我正在开发一个程序,它将对象存储在LinkedList中,然后通过搜索所述对象的字段来搜索列表中的特定对象以匹配它们并创建价格,但我无法弄清楚如何实际完成此任务。我附上了代码片段,以了解我正在做的事情的基础,并且非常感谢任何帮助。

public class Database {
LinkedList<ProduceItem> list = new LinkedList<ProduceItem>();

public Database() throws FileNotFoundException{
    String name = "PriceList.txt";
    File file = new File(name); //Create file object


    Scanner inputFile = new Scanner(file);  //Create Scanner object to read from file
    String line = null; //String for input

    while(inputFile.hasNextLine()){                                     //While loop to sort through the file
            line = inputFile.nextLine();                                //Read line from file
            if(line.charAt(0) == 'V'){
                StringTokenizer tokenizer = new StringTokenizer(line, ",");
                Vegtable veg = new Vegtable();
                tokenizer.nextToken();                                  //Burn first token to eliminate identifier
                veg.setCode(tokenizer.nextToken());
                veg.setName(tokenizer.nextToken());
                veg.setPrice(Float.parseFloat(tokenizer.nextToken()));
                list.add(veg);
            }
            else{
                StringTokenizer tokenizer = new StringTokenizer(line, ",");
                Fruit fru = new Fruit();
                tokenizer.nextToken();
                fru.setCode(tokenizer.nextToken());
                fru.setName(tokenizer.nextToken());
                fru.setPrice(Float.parseFloat(tokenizer.nextToken()));
                list.add(fru);

            }
    }   
    inputFile.close();
}

}

1 个答案:

答案 0 :(得分:0)

你可以做这样的事情

for(ProduceItem item : list) {

   if(item.name.equals(searchKey) {
      //perform calculations or display to screen here
   }

}