如何将构造函数中的ArrayList传递给另一个类

时间:2015-07-04 17:57:35

标签: java arraylist

我是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){

   }
}

3 个答案:

答案 0 :(得分:1)

如果我很清楚您想要访问另一个类中的ArrayList?如果在这种情况下,您可以在声明私有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;
}

答案 1 :(得分:0)

CustomerAcc类的构造函数更改为:

 public CustomerAcc(ArrayList<String> custName, ArrayList<String> custZip, int count){

}

您还将custName和custZip定义为

     ArrayList custName = new ArrayList();
     ArrayList custZip = new ArrayList();

这是不正确的。你必须在ArrayList中指定对象的类型(我想它们现在是字符串。)

将其定义为:

 ArrayList<String> custName = new ArrayList<>();

答案 2 :(得分:0)

语法时,您可以将构造函数代码定义更改为 -

public CustomerAcc(ArrayList<String> custName, ArrayList<String> custZip, int count){

}

查看代码,您可以使用Map<String, String>来存储用户名及其zip,而不是使用两个列表。

另外请注意,您确定要构建单个CustomerAcc对象,将客户列表及其邮政编码作为输入吗?