当大小未知时,如何在循环中填充ArrayList?

时间:2013-07-16 07:00:55

标签: java android

我必须填写一些对象的成员,但我不知道它们有多少。这就是我因为动态大小而使用ArrayList的原因。但我不知道如何在ArrayList中填充这些对象。我正在从文件中逐行阅读,如果我找到了匹配模式,我必须创建新对象并用数据填充它。

//read data from file to BufferedReader, that we can read out single line by line
BufferedReader mBufferedReader = new BufferedReader(new FileReader(mFile));
String line;

while ((line = mBufferedReader.readLine()) != null) {
    //pattern "name" for searching points
    Pattern pattern = Pattern.compile("\"(.*?)\"");
    //array of delimited Strings separated with comma 
    String[] delimitedStrings = line.split(",");

    //if we find "name" of point, get code, lat and lon of that point
    Matcher matcher = pattern.matcher(line);

    if (matcher.find()) {
        String name = delimitedStrings[0];
        mData.add(new myData().name = name);
        String code = delimitedStrings[1];
        mData.add(new myData().code = code);

    }
}

myData类具有成员String name,例如String代码。我需要使用add方法这样的东西,但这不起作用。谢谢!

3 个答案:

答案 0 :(得分:2)

这不会编译:

if (matcher.find()) {
    String name = delimitedStrings[0];
    mTaskData.add(new myData().name = name);                

    String code = delimitedStrings[1];
    mTaskData.add(new myData().code = code);                    

}

应该是这样的:

if (matcher.find()) {
    String name = delimitedStrings[0];
    myData md = new myData();
    md.name = name; // or use setter like md.setName(name)
    mTaskData.add(md);                

    String code = delimitedStrings[1];
    md.code = code;
    mTaskData.add(md);                    

}

答案 1 :(得分:2)

有点模糊,但也许你的意思是

if (matcher.find()) {
    String name = delimitedStrings[0];
    String code = delimitedStrings[1];

    mTaskData.add(new MyData(name, code));                    
}

其中MyData类的构造函数定义为

public class MyData {

    private String name;
    private String code;

    public MyData (String name, String code) {
        this.name = name;
        this.code = code;
    }

    // getters/setters()
}

此外,Pattern不会改变,因此应移出文件阅读器循环。

// compile the pattern just once (outside the loop)
Pattern pattern = Pattern.compile("\"(.*?)\"");

while ((line = mBufferedReader.readLine()) != null) {

答案 2 :(得分:1)

List<mData> mData = new ArrayList<>();

mData.add(new mData(code));

使用参数String code

在mData中创建一个构造函数