我是 java 新手,正在尝试使用 ArrayList。从 Main 方法中,我想将 ArrayList 传递给另一个类 CustomerAcc。我需要帮助如何传递 >ArrayList 以及如何在此处的类 Customer 代码中获取 ArrayList
import java.io.*;
import java.util.*;
import java.lang.Object;
public class CustomerMain {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> custName = new ArrayList<String>();
ArrayList<String> custZip = new ArrayList<String>();
double count = 0;
boolean done = false;
System.out.print("Please enter Customer name or 'X' to exit: ");
Scanner in = new Scanner(System.in);
// Gets user input for name and zip code
while (in.hasNext() && !done) {
String checkInput = in.next();
if (checkInput.equalsIgnoreCase("X")) {
done = true;
}
else {
custName.add(checkInput);
System.out.print("Please enter Zip code: ");
custZip.add(in.next());
count++;
System.out.print("\nPlease enter Customer Name or 'X' to `enter code here`exit: ");
}
}
//Sending the user input data to CustomerAcc class
CustomerAcc custRecord = new CustomerAcc(custName, custZip, count);
}
}
CustomerAcc 类:
public class CustomerAcc extends CustomerMain {
public static void CustomerAcc(String custName, String custZip, int count){
}
}
最佳答案
如果我很清楚你想访问另一个类中的ArrayList?如果在这种情况下,您可以在声明私有(private) ArrayList 变量时使用 getter 和 setter 技术。
private ArrayList<String> custName = new ArrayList<String>();
private ArrayList<String> custZip = new ArrayList<String>();
public void setCustName(ArrayList custName){
this.custName = custName;
}
public ArrayList geCustName(){
return custName;
}
public void setCustZip(ArrayList custZip){
this.custZip = custZip;
}
public ArrayList geCustZip(){
return custZip;
}
关于java - 如何将构造函数中的ArrayList传递给另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31223625/