我是Java的新手,曾经看过这些帖子,但发现示例程序使我难以理解。请提供一个关于如何将ArrayList从一个类传递到另一个类的简单示例,这样我将非常感激,这样我就可以知道发生了什么。
下面我写的示例代码读取一个txt文件(可以是任何字符串字符),我只列出了五种颜色。该程序将它们显示到控制台,但我只想将数组传递给第二个程序
感谢您的指导-让我感到困惑!
//First program that reads in a text file and displays it to the screen
//
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
// reading a file as a list using ArrayList (1 dim Array)
public class ReadArrayList {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\user\\IdeaProjects\\test.txt"));
ArrayList<String> myList = new ArrayList<>();
String line = null;
while ((line = br.readLine()) != null) {
myList.add(line);
}
//create object of second class to store array values when they get passed to it
//is this correct way - I am not sure?
ClassReceiveArrayA cpa = new ClassReveiveArrayA();
PassArray(myList);
br.close();
}
public static void PassArray(ArrayList<String> words)
{
for (String w : words)
{
System.out.println(w);
}
}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++
// second program
//
// I want this program to receive the arrayList from class ReadArrayList above
//and display it to the console
import java.util.ArrayList;
// To receive ArrayList from ReadArrayList
public class ClassReceiveArrayA {
// can put a for loop here to print array to the screen
//when I figure out how to do it!
//
}