繁体   English   中英

ArrayList-可以读出元素名称吗?

[英]ArrayList - possible to read out the element name?

大家好!

我的项目更大,所以我决定将其简短一点,只显示我当前拥有的问题代码。 首先,在控制台上进行即时编程。 从扫描仪读取六个字符串,然后将它们保存到变量中,然后进行有效性检查(长度,特殊符号等)。 因此,我决定使用额外的方法check_newCustomer()来完成此操作。 我使用ArrayList作为一个值返回更多值。 现在,我需要在main()函数或任何其他将新客户写入数据库的方法中捕获输入。 现在的问题是我不知道如何在其他方法中引用userID,firstname,secondname...。 我可以参考一个索引。 但是当我可以使用变量名来引用它时,我会更喜欢它。 因此,使用其他方法处理字符串要容易得多。 可能?

public static void main(String[] args) {
    ArrayList<String> newCustomer = new ArrayList<String>(); 
    check_newCustomer (newCustomer);
}


public static void check_newCustomer(ArrayList<String> newCustomer) throws IOException {
    String userID = null;
    String firstname = null;
    String secondname = null;
    String street = null;
    String zipcode = null;
    String city = null;

    // validity check before I fill the input fields
    ...

    // fill arraylist
    newCustomer.add(userID);
    newCustomer.add(firstname);
    newCustomer.add(secondname);
    newCustomer.add(street);
    newCustomer.add(zipcode);
    newCustomer.add(village);
}

谢谢!

不, ArrayList的值只是一个参考。 您最初使用其他变量引用它的事实是无关紧要的。

可以使用Map<String, String>代替...但是拥有一个Customer类,其中包含用于各种信息的字段会清洁。 如果需要多个客户,则可以有一个List<Customer>

一个人需要创建一个类Customer,只需一组字段即可。 而不是字符串列表。

public class Customer {
    String userID;
    String firstname;
    String secondname;
    String street;
    String zipcode;
    String city;
}

并在代码中:

Customer newCustomer = new Customer();
newCustomer.userID = ....
System.out.println(newCustomer.userID);

当您通过check_newCustomer (newCustomer); 您只传递数组列表的副本。 在这种情况下,原始数组列表newcustomer保持原样,而范围在方法check_newCustomer内的新副本将存储所有字符串。 您可以为客户创建一个新类,也可以创建一个类并将数组列表作为类变量,将check_newCustomer作为类方法。 在后一种情况下,这很简单。

    class customer
        ArrayList<String> newCustomer;
        public static void main(String[] args) {

                newCustomer = new ArrayList<String>(); 
                check_newCustomer ();
            }


        public static void check_newCustomer() throws IOException {
                String userID = null;
                String firstname = null;
                String secondname = null;
                String street = null;
                String zipcode = null;
                String city = null;

                // validity check before I fill the input fields
                ...

                // fill arraylist
                newCustomer.add(userID);
                newCustomer.add(firstname);
                newCustomer.add(secondname);
                newCustomer.add(street);
                newCustomer.add(zipcode);
                newCustomer.add(village);
                }
}

这必须工作。

暂无
暂无

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

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