简体   繁体   中英

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. 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:

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:

  1. Delcare the list as a class level variable and make it public
class ListClass {
  public List csvList;

  ...
}
  1. Declare the list as a private class variable and have an accessor
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.

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.

public class OtherClass{
  public static void main(String[] args){
  ListClass listClass = new ListClass();
  List newList = listClass.list;// your list
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM