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

标签 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){

   }
}

最佳答案

如果我很清楚你想访问另一个类中的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/

相关文章:

java - 在java中使用数组陷入困境

java - 如何反序列化大 JSON 文件 (~300Mb)

Java 停止 GIF 动画

java 创建 arraylist 一个递增并存储增量的抽象方法

java - 按 HashMap 的值(按映射的值比较)对 HashMap 的数组列表进行排序

java - getSupportLoadManager() 已弃用

java - 在客户端使用带有 GWT 的 3rd 方库?

java - 当应用程序关闭时 AltBeacon 继续扫描

Java 日期方法?类? joptionpane/输出/显示数据库中数组列表中的对象?

java - ArrayList:java.lang.IndexOutOfBoundsException:索引:283,大小:283