[英]Accessing array list elements from another class
I have a main class which has an ArrayList
. 我有一个具有
ArrayList
的主类。 This ArrayList
has a set of values stored via iteration. 该
ArrayList
具有一组通过迭代存储的值。 I need to use this ArrayList
(fileList & directoryList) value in another class. 我需要在另一个类中使用此
ArrayList
(fileList&directoryList)值。 How can I achieve this? 我该如何实现? I do not want to move the
ArrayList
into another class. 我不想将
ArrayList
移到另一个类中。
package com.filehandler;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class FileFinder {
public static void main(String[] args) {
// TODO Auto-generated method stub
int directoryCount = 0;
/* Declare Lists for Files & Directories */
List<String> fileList = new ArrayList<String>();
List<String> directoryList = new ArrayList<String>();
// enter code here
/* Set file location */
File myFolder = new File("O:\\The Ultimate Book Shelf\\Technical");
File[] myFileList = myFolder.listFiles();
/* Iterate the folder to get the details of Files & Folders */
for (int count = 0; count < myFileList.length; count++) {
if (myFileList[count].isFile()) {
// System.out.println("File " + myFileList[count].getName());
fileList.add(myFileList[count].getName());
} else if (myFileList[count].isDirectory()) {
directoryCount++;
// System.out.println("Directory " +
// myFileList[count].getName());
directoryList.add(myFileList[count].getName());
} else {
System.out
.println("There are no files or directories in the mentioned path. Please verify the folder location.");
}
}
System.out.println("Total Files : "
+ (myFileList.length - directoryCount));
System.out.println("Total Directories :" + directoryCount);
System.out.println(fileList);
System.out.println(directoryList);
}
}
Your other class can either accept two ArrayLists in its own constructor or as parameters for a specific method, depending on what you are trying to do. 您的其他类可以在自己的构造函数中接受两个ArrayList,也可以作为特定方法的参数,具体取决于您要执行的操作。 By passing them as parameters you will actually pass a reference to the ArrayLists you created in you main function, therefore the other class will be able to read the values inside.
通过将它们作为参数传递,您实际上将传递对您在主函数中创建的ArrayList的引用,因此另一个类将能够读取其中的值。
It depends how would the array be used in the second class. 这取决于如何在第二类中使用数组。 You have the following options.
您有以下选择。
For 1, you can simply pass the array to the method. 对于1,您可以简单地将数组传递给方法。 For 2, you can pass the array to a constructor and initialize the member variables in the class.
对于2,您可以将数组传递给构造函数,并初始化类中的成员变量。 For 3, you can set like
SecondClass.fileList = myFileList;
对于3,您可以设置诸如
SecondClass.fileList = myFileList;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.