“列表无法解析或不是字段”

时间:2016-11-23 16:48:04

标签: java arraylist

我正在向一个arraylist写对象,我需要访问该对象的特定元素。但是,我不断收到这个恼人的错误。我的加载类只有对象中元素的setter。我如何解决它?我只是想将该特定元素分配给变量。

驱动程序类

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

public class Driver {

public static void main(String[] args) throws IOException 
        {
            BufferedReader file = new BufferedReader(new          FileReader("test.txt"));
            ArrayList<Load> list = new ArrayList<Load>();
            String line;
            String[] words=new String[3] ;
            Load load = new Load();
            int x =0;
            while((line=file.readLine())!=null)
            {   
            words=line.split("\t");

            String process=words[0];
            int arrivalTime=Integer.parseInt(words[1]);
            int serviceTime=Integer.parseInt(words[2]);

            list.add(new Load(process,arrivalTime,serviceTime));
            x++;
            }
    }
    }

RoundRobin课程

public class RoundRobin {


    Driver data = new Driver();
    String a =((Load) data.list.get(0)).process; //This is where the error occurs
}

3 个答案:

答案 0 :(得分:1)

您可以在main中将列表定义为本地变量:

public static void main(String[] args) {
    ....
    ArrayList<Load> list = new ArrayList<Load>();

仅在main范围内可用。

你需要让它成为一个班级成员:

public class Driver {
    private List<Load> list = new ArrayList<Load>();

    public List<Load> getList() {
        return list;
    }
    ....
}

然后你打电话

String a =((Load) data.getList().get(0)).process;

你可能不希望像这样直接暴露list,但这是另一回事。

答案 1 :(得分:0)

这就是你的Driver类应该是这样的:

public class Driver {

    ArrayList<Load> list = new ArrayList<Load>();

    public void initializeList() throws IOException{
        BufferedReader file = new BufferedReader(new FileReader("test.txt"));
        String line;
        String[] words=new String[3] ;
        Load load = new Load();
        int x =0;
        while((line=file.readLine())!=null){   
            words=line.split("\t");
            String process=words[0];
            int arrivalTime=Integer.parseInt(words[1]);
            int serviceTime=Integer.parseInt(words[2]);
            list.add(new Load(process,arrivalTime,serviceTime));
            x++;
        }
    }

    public List<Load> getList() {
        return list;
    }
}

然后在你的RoundRobin课程中:

public class RoundRobin {
...
    Driver data = new Driver();
    data.initializeList();
    String a =((Load) data.getList.get(0)).process; 
...
}

答案 2 :(得分:-1)

通过将声明从方法移动到类级别和

来使这个列表引用到类

static ArrayList list = new ArrayList();