繁体   English   中英

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

[英]how to pass ArrayList in a constructor to another class

我是java的新手,正尝试在ArrayList上工作。 从Main方法,我想>将ArrayList传递给另一个类CustomerAcc。 我需要帮助,如何通过> ArrayList,然后如何在此处的客户代码类中获取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? 如果是这种情况,则可以在声明私有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;
}

将您的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<>();

说话时的语法可以将构造函数代码定义更改为-

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

}

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

单独说明,您确定要构建单个CustomerAcc对象,将客户列表及其邮政编码作为输入吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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