简体   繁体   English

在集合Java中存储和查询对象

[英]Store and query objects in collection java

I'm working on a java project right now and am stuck. 我正在处理一个Java项目,现在被卡住了。 I'm trying to figure out how to first store a person object that has several elements like first name, last name, and ID. 我试图弄清楚如何首先存储具有多个元素(例如名字,姓氏和ID)的人员对象。 I know it's possible to create different collections for each part of the object but I'm wondering is it possible to create and query all elements in one collection? 我知道可以为对象的每个部分创建不同的集合,但是我想知道是否可以在一个集合中创建和查询所有元素? That is to say, after storing the objects in the collection, I want to interate through the collection to search for first name, last name, and ID. 也就是说,在将对象存储在集合中之后,我想遍历集合以搜索名字,姓氏和ID。

This is my current code: 这是我当前的代码:

  public static void processRecords(String filenameIn)throws Exception{ 
    Scanner input = new Scanner(new File("students_mac.txt")); //retrieves data from file and stores
    input.nextLine();

    while (input.hasNextLine()) { //enters loop to process individual records and print them
            String line = input.nextLine(); 
            String[] tokens=line.split("\t"); // splits lines by tabs
            if(tokens.length!=4) 
                continue;
            Person student = new Person(FirstName, LastName, ID, Year);
            List<Person> list = new LinkedList<Person>();
            list.add(student);
        }

    List<Person> list=new LinkedList<Person>();
        for(Person student : list){
            System.out.println(student);
        } 

All you need is to move List<Person> list = new LinkedList<Person>(); 您所需要做的就是移动List<Person> list = new LinkedList<Person>(); out of while loop. 退出while循环。

Scanner input = new Scanner(new File("students_mac.txt")); //retrieves data from file and stores
input.nextLine();

List<Person> list = new LinkedList<Person>();

while (input.hasNextLine()) { //enters loop to process individual records and print them
        String line = input.nextLine(); 
        String[] tokens=line.split("\t"); // splits lines by tabs
        if(tokens.length!=4) 
            continue;
        list.add(new Person(FirstName, LastName, ID, Year));
    }

    for(Person student : list){
        System.out.println(student);
    } 

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

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