如何将字符串转换为用户定义的ArrayList

时间:2017-02-02 18:08:30

标签: java arraylist

我有一个逗号分隔的学生值字符串,我需要添加到学生的ArrayList中。但是,我目前所做的并不起作用,而且我不确定如何继续。

String s;
BufferedReader in = new BufferedReader(new FileReader(path));
s = in.readLine();
ArrayList<Student> slist = new ArrayList<>();
while (s != null){
    slist.add(s);
    s = in.readLine();
}

slist.add(s)无效,因为String无法转换为ArrayList

3 个答案:

答案 0 :(得分:0)

看到你如何发布没有关于如何创建学生的代码,这将是我对如何解决问题的最佳猜测。

String s;
BufferedReader in = new BufferedReader(new FileReader(path));
s = in.readLine();
ArrayList<Student> slist = new ArrayList<>();
while (s != null){
    slist.add(new Student(s)); //creat a new student based on the string
    s = in.readLine();
}

如果您有一个以String作为参数的Student类的构造函数,那么这将有效。就像每个人都说你正在创建一个学生的ArrayList而不是字符串。如果要将其添加到列表中,则必须创建Student对象。

答案 1 :(得分:0)

它不起作用,因为您的ArrayList接受Student类型的元素,但您尝试添加String类型的元素。

假设您的学生班级与您尝试添加的字符串相关,例如学生姓名:

class Student{
    private String name;
    public Student(String name){
        this.name = name;
    }
}

然后您可以将其添加为:

while (s != null){
    slist.add(new Student(s));  //create student obj from s, then add to list
    s = in.readLine();
}

答案 2 :(得分:0)

如下:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class Main {

    private static class Student {
        private String firstName;
        private String lastName;

        public Student(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public Student(String line) {
            String[] parts = line.split(",");
            if (parts.length > 0 && parts.length == 2) {
                this.firstName = parts[0];
                this.lastName = parts[1];
            }
        }

        public String getFirstName() {
            return firstName;
        }

        public Student setFirstName(String firstName) {
            this.firstName = firstName;
            return this;
        }

        public String getLastName() {
            return lastName;
        }

        public Student setLastName(String lastName) {
            this.lastName = lastName;
            return this;
        }

        @Override
        public String toString() {
            return this.firstName + " " + this.lastName;
        }
    }

    private static final String fileName = "fileName.txt";

    public static void main(String[] args) throws IOException {
        String s;
        BufferedReader in = new BufferedReader(new FileReader(fileName));
        s = in.readLine();
        ArrayList<Student> slist = new ArrayList<>();

        while (s != null) {
            slist.add(new Student(s));
            s = in.readLine();
        }

        slist.forEach(System.out::println);
    }
}