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

时间:2017-04-26 23:16:28

标签: java loops object collections

我现在正在研究一个java项目而且卡住了。我试图弄清楚如何首先存储一个具有多个元素的人物对象,如名字,姓氏和ID。我知道可以为对象的每个部分创建不同的集合,但我想知道是否可以创建和查询一个集合中的所有元素?也就是说,在将对象存储在集合中之后,我想通过集合进行交互来搜索名字,姓氏和ID。

这是我目前的代码:

  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);
        } 

1 个答案:

答案 0 :(得分:0)

您只需将List<Person> list = new LinkedList<Person>();移出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);
    }