[英]How can I access this list in another class?
I have created a list of items from a CSV file, but am not sure how to access this list in another class.我已经从 CSV 文件创建了一个项目列表,但不确定如何在另一个类中访问此列表。 I have created the instance of the list class in the new class, but have not been able to find a way to access the list.
我已经在新类中创建了列表类的实例,但是一直找不到访问列表的方法。
public class ListClass {
public static void main(String[] args) throws IOException {
CSVReader csvReader = new CSVReader();
List list = csvReader.Read("csvFile.csv");
}
}
I have been able to print the list, and so I know that it's definitely working, but I'm just not sure how I'd access it in another class.我已经能够打印列表,所以我知道它肯定有效,但我不确定如何在另一个类中访问它。 The new class is currently empty, aside from the following;
除了以下内容之外,新类目前是空的;
ListClass listClass = new ListClass();
You should store the list as a private instance variable in your ListClass and create a getter for it:您应该将列表作为私有实例变量存储在 ListClass 中并为其创建一个 getter:
public class ListClass {
private List list = null;
public static void main(String[] args) {
try {
new ListClass();
} catch(IOException ioEx){
// error handling
}
}
public ListClass() throws IOException {
CSVReader csvReader = new CSVReader();
list = csvReader.Read("csvFile.csv");
}
public List getList(){
return list;
}
}
Then you can access it from your other class:然后你可以从你的其他班级访问它:
try {
ListClass listClass = new ListClass();
List list = listClass.getList();
} catch(IOException ioEx){
// error handling
}
You need to make the list accessible to other classes by doing one of the following:您需要通过执行以下操作之一使其他类可以访问该列表:
class ListClass {
public List csvList;
...
}
class ListClass {
private List csvList;
public List getCsvList() {
return this.csvList;
}
...
}
There are a lot of other ways to access a class variable.还有很多其他方法可以访问类变量。 The second one is a very common way of doing it.
第二种是一种非常常见的做法。
1 )Add your list as a Field of ListClass and put your initialization inside the constructor. 1 ) 将您的列表添加为 ListClass 的字段并将您的初始化放在构造函数中。
public class ListClass {
public List list;
ListClass(){
try{
CSVReader csvReader = new CSVReader();
list = csvReader.Read("csvFile.csv");
}catch(IOException e){
//handle the exception
}
}
}
2) create an object of ListClass in OtherClass. 2)在OtherClass中创建ListClass的对象。
public class OtherClass{
public static void main(String[] args){
ListClass listClass = new ListClass();
List newList = listClass.list;// your list
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.