简体   繁体   English

如何初始化数组列表中的对象

[英]How to intialise objects in the array list

I am trying to initialize objects in my ArrayList我正在尝试初始化我的 ArrayList 中的对象

The following is my code and what it does is that it receives an ArrayList, already defined in the main method.以下是我的代码,它的作用是接收一个已在 main 方法中定义的 ArrayList。 However, it is not executing the readInput method in the code below.但是,它没有执行下面代码中的 readInput 方法。 readInput is a method declared in another class called customer that takes in keyboard input from the user. readInput 是在另一个名为 customer 的类中声明的方法,它接收用户的键盘输入。 Its a complete class BTW.它是一个完整的类 BTW。 I believe that there is no object in the ArrayList at the moment as i have run some test to see whats the problem.我相信目前 ArrayList 中没有对象,因为我已经运行了一些测试来查看问题所在。 Im new to using Arraylist.我是使用 Arraylist 的新手。 Therefoere i am unsure of how to solve this proble.因此,我不确定如何解决这个问题。 What custs.set(i, new customer());什么 custs.set(i, new customer()); does is actually to initialize the object in index. do实际上是初始化索引中的对象。

public static void freeCustomer(ArrayList<customer> custs,
                                ArrayList<supplement>supps)
{
    for(int i=0;i<custs.size();i++)
    {

        custs.set(i, new customer());
        custs.get(i).readInput();
        for(int s=0;s<supps.size();s++)
        {
         supps.set(s, new supplement());
         supps.get(s).readInput();
        }
    }
}

If I understood right,you want to add user input from a customer method.I would use add method.I just made a fast example of add method.From here you can expand to loops,etc.如果我理解正确,您想从客户方法中添加用户输入。我将使用添加方法。我刚刚制作了一个添加方法的快速示例。从这里您可以扩展到循环等。

 public static void freeCustomer(ArrayList<customer> custo,customer c)
{
 custo.add(new customer(c.readInput()));

 }


    public static void main(String[] args) {   
        ArrayList<customer> custo = new ArrayList<customer>();
        customer c=new customer("");

        freeCustomer(custo,c);


        }
    }

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

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